我有一个程序,基本上是读取文本文件并计算每行中每个单词出现的次数。使用 ifstream 从文本文件读取时一切正常,但是如果没有在命令行输入文件名,则需要从 stdin 中读取。
我目前使用以下代码打开和读取文件:
有没有一种方法可以将cin分配给ifstream,并在argc > 1失败时简单地添加else语句,而不是像这样重复代码?我还没有找到一种方法来做到这一点。
我目前使用以下代码打开和读取文件:
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语句,而不是像这样重复代码?我还没有找到一种方法来做到这一点。