C++ Primer的10.3.9单词转换

2014-07-19 23:03:28 · 作者: · 浏览: 73

  对C++ Primer的10.3.9单词转换的思考

  #include

  #include

  #include

  #include

  #include

  using namespace std;

  ifstream& open_file(ifstream&,const string&);

  int main(int argc, char **argv)

  {

  map trans_map;

  string key, value;

  if (argc!= 3)

  throw runtime_error("wrong number of arguments");

  ifstream map_file;

  if (!open_file(map_file, argv ))

  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 ))

  throw runtime_error("no input file");

  string line;

  while (getline(input, line))

  {

  istringstream stream(line);

  string word;

  bool firstword = true;

  while (stream >> word) {

  map::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 存储着第二个命令行参数字符串,argv[argc-1]存储着最后一个命令行参数字符串。一般来说,argv[0]存储的是当前程序的路径与全称。

  argc和argv就是一个名字,可以改变的,如写成arc和arv,丝毫不影响。