C++ Primer第四版中的318页有如下程序:
#include<map>
#include<string>
#include<fstream>
#include<sstream>
#include <iostream>
using namespace std;
ifstream& open_file(ifstream &in, const string &file)
{
in.close();
in.clear();
in.open(file.c_str());
return in;
}
int main(int argc,char **argv)
{
map<string, string> trans_map;
string key, value;
if (argc != 3)
throw runtime_error("wrong number of arguements!!");
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;
}
但写完这段程序后,你可能会有所疑问,在哪调用int main(int argc, char **argv)函数呢?
方法是:在Dos环境下调用带形参的main()函数,具体方法如下:
1、首先在Debug目录下新疆两个.txt文件,一个存储你需要转换的文件,一个存储单词转换的文件;
2、打开dos界面,由于我的程序形成的可执行文件是放到 “G:\C++练习\lianxi\Debug”目录下的,所以首先进入到该目录下;
3、在dos环境下输入,lianxi.exe yuanfile.txt transfile.txt ,回车即可看到结果;
具体界面如下: