#include <iostream>
#include <string>
#include <map>
#include <fstream>
#include <sstream>
using namespace std;
ifstream& open_file(ifstream&,const string&);
int main(int argc, char **argv)
{
map<string, string> trans_map;
string key, value;
if (argc!= 3)
throw runtime_error("wrong number of arguments");
ifstream map_file;
if (!open_file(map_file, argv[1]))
throw runtime_error("no transformation file");
while (map_file>>key>>value)
trans_map.insert(make_pair(key, value));
ifstream input;
if (!open_file(input, argv[2]))
throw runtime_error("no input file");
string line;
while (getline(input, line))
{
istringstream stream(line);
string word;
bool firstword = true;
while (stream >> word) {
map<string, string>::const_iterator map_it =trans_map.find(word);
if (map_it != trans_map.end())
word = map_it->second;
if (firstword)
firstword = false;
else
cout << " ";
cout << word;
}
cout << endl;
}
return 0;
}
這篇代碼有幾個知識點可以復習一下:
1.main函數的形參
main(int argc, char **argv);
argc是一個整型變量,指的是命令行輸入參數的個數,argv是字符串數組,它包含argc個字符串,每個字符串存儲著一個命令行參數,其也可以寫作char *argv[]。如argv[0]存儲著第一個命令行參數字符串,argv[1]存儲著第二個命令行參數字符串,argv[argc-1]存儲著最後一個命令行參數字符串。一般來說,argv[0]存儲的是當前程序的路徑與全稱。
argc和argv就是一個名字,可以改變的,如寫成arc和arv,絲毫不影響。