【发布时间】:2014-05-27 20:00:00
【问题描述】:
我有一个程序,它基本上读取一个文本文件并计算每行中每个单词的出现次数。使用 ifstream 从文本文件读取时一切正常,但是,如果未在命令行中输入文件名,我需要改为从标准输入读取。
我目前使用以下打开和读取文件:
map<string, map<int,int>,compare> tokens;
ifstream text;
string line;
int count = 1;
if (argc > 1){
try{
text.open(argv[1]);
}
catch (runtime_error& x){
cerr << x.what() << '\n';
}
// Read file one line at a time, replacing non-desired char's with spaces
while (getline(text, line)){
replace_if(line.begin(), line.end(), my_predicate, ' ');
istringstream iss(line);
// Parse line on white space, storing values into tokens map
while (iss >> line){
++tokens[line][count];
}
++count;
}
}
else{
while (cin) {
getline(cin, line);
replace_if(line.begin(), line.end(), my_predicate, ' ');
istringstream iss(line);
// Parse line on white space, storing values into tokens map
while (iss >> line){
++tokens[line][count];
}
++count;
}
有没有办法将 cin 分配给 ifstream 并在 argc > 1 失败时简单地添加一个 else 语句,然后使用相同的代码而不是像这样复制?我还没有找到方法来做到这一点。
【问题讨论】: