菜鸟开始学习c++ primer,对于书本里的程序常常都读得一知半解,却编译不过去,决定把学习过程记录下来,帮助自己解决问题,加深理解,让自己有动力坚持下去
1.找不到main入口
我建的项目是一个空项目,在编译的时候找不到main()方法,虽然我点击文件=》新建=》文件=》Visual C++里面的C++文件(.cpp),但是建好的cpp文件却不是在项目里面。
解决办法:在建好的项目点击右键=》添加=》新建项
2.控制台输入参数:
这个程序要求有3个运行参数,即argc==3。我是在vs2010里运行的,需要设置一下运行时的参数。在项目属性里面配置属性-》调试-》命令参数里面写上你的参数,如:e:\\map.txte:\\input.txt。或者在cmd执行该项目生成的exe文件:StudyMap.exee:\\map.txt e:\\input.txt
3. open_file函数是书本P256 8.4.3中出现的。需要添加代码。
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <string>
using namespace std;
int main(int argc, char **argc)
{
map<string,string> trans_map;
string key, value;
if (argc !=3)
throw runtime_error("wrong number of arguments");
//open transformation file and check that open succeeded
ifstream map_file;
if(!open_file(map_file,argv[1]))
throw runtime_error("no transformation file");
//read the transformation map and build the map
while(map_file>>key>>value)
trans_map.insert(make_pair(key, value));
//ok, now we're ready to do the transformations
//open the input file and check that the open succeeded
ifstream input;
if(!open_file(input,argc[2]))
throw runtime_error("no input file");
string line; //hold each line from the input
//read the text to transform it aline at a time
while (getline(input, line))
{
istringstream stream(line); //read the line a word at a time
string word;
bool firstword=true; //这个变量没看懂,什么情况下会发生false-》true的变化?????
while (stream>>word)
{
//ok:the actual mapwork, this part is the heart of the program
map<string, string>::const_iterator map_it=
trans_map.find(word);
//if this word is in the transformation map
if (map_it != trans_map.end)
//replace it by the transformation value in the map
word=map_it->second;
if (firstword)
firstword=false; //问题和上面一样
else
cout<<" "; //print space between words
cout<<word;
}
cout<<endl; //done with this line of input
}
return 0;
}