各位高手,帮我调试个小程序,我求求你了...
#include <iostream>
#include <map>
#include <fstream>
#include <vector>
#include <string>
#include <stdexcept>
#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))
{
string word;
istringstream stream(line);
bool firstword=true;
while(stream> > word)
{
map <string,string> ::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;
}
}
ifstream& open_file(ifstream &in,const string &file)
{
in.close();
in.clear();
in.open(file.c_str());
return in;
}
/*各位深刻理解了C/C++的朋友,请告诉我如何才能高效率的学习, 不知道自己该如何
去学,每天就是机械式的看书写代码,根本都不知道自己是不是真的懂,但是就是这
样不断的看不断的照着书写,我觉得自己已经很努力了,白天在学校上完课,回来就自学C++,
短短3个月,同学现在都可以用JBuilder编写Window应用程序了,他们老是打击我学C++,
我真想用C++写他们搞不定的程序回击他们,可我C++语言还不熟,更不要提VC/MFC了..,
是不是他们都理解了传说中的编程思想,所以学习效率这么高,是不是学习C++本来就没效率,
还是我不够努力啊,在此领域的成功者,请说说你们的学习心得吧,
教导教导我这种在还没真正悟道的人啊,感激不尽啊!!
申明本人不歧视任何语言,有人使用就证明它有价值,但每人都有自己的兴趣,
想打口水战的::鄙视你*/
[解决办法]
你的程序基本没有大问题,估计你要做啥,稍微改了一下。
注意,你运行程序的时候,你要输入两个参数(文件名), 第一个文件名是你要把那个文件中的key 和 value对读入map 中, 第二个文件名是你要找到这第二个文件中的key是不是在 map中,如果在的话,就打印出他对应的value来。
我试了一下, 程序没有问题
iclx012$ ./a.out mapfile inputfile
a
d
e
ff
iclx012$ more mapfile
a aa
b bb
c bb
d dd
e ee
ff ffff
iclx012$ more inputfile
a
d
e
ff
付上修改的程序:
=====================
#include <iostream>
#include <map>
#include <fstream>
#include <vector>
#include <string>
#include <stdexcept>
#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;
try
{
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));
}
}
catch (runtime_error rex)
{
cout < < "Catching: runtime_error: \ " " < < rex.what() < < "\ " " < < endl;
}
ifstream input;
if(!open_file(input,argv[2]))
throw runtime_error( "no input file! ");
string line;
while(getline(input,line))
{
string word;
istringstream stream(line);
while(stream> > word)
{
map <string,string> ::iterator map_it=trans_map.find(word);
//if map_it is not the end, it means it finds a matching.
if(map_it!=trans_map.end())
{
word=map_it-> second;
cout < <word;
}
}
cout < <endl;
}
}
ifstream& open_file(ifstream &in,const string &file)
{
in.close();
in.clear();
in.open(file.c_str());
return in;
}