CGu*_*utz 4 c++ stdin input ifstream
我有一个基本上读取文本文件的程序,并计算每行上每个单词的出现次数.使用ifstream从文本文件中读取时,一切正常,但是,如果未在命令行中输入文件名,我需要从stdin读取.
我目前使用以下内容打开并读取文件:
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;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法将cin分配给ifstream,如果argc> 1失败,只需添加一个else语句,之后使用相同的代码而不是像这样重复?我找不到办法做到这一点.
使阅读部分成为自己的功能.通过一个ifstream或cin它.
void readData(std::istream& in)
{
// Do the necessary work to read the data.
}
int main(int argc, char** argv)
{
if ( argc > 1 )
{
// The input file has been passed in the command line.
// Read the data from it.
std::ifstream ifile(argv[1);
if ( ifile )
{
readData(ifile);
}
else
{
// Deal with error condition
}
}
else
{
// No input file has been passed in the command line.
// Read the data from stdin (std::cin).
readData(std::cin);
}
// Do the needful to process the data.
}
Run Code Online (Sandbox Code Playgroud)