从文本文件或标准输入中读取
我有一个程序,该程序基本上读取一个文本文件并计算每行中每个单词的出现次数.使用ifstream读取文本文件时,一切正常,但是,如果未在命令行上输入文件名,则需要从stdin读取.
I have a program that basically reads a text file and counts the number of occurrences of each word on each line. Everything works properly when reading from a text file using an ifstream, however, if a file name is not entered on the command line, I need to read from stdin instead.
我使用以下命令打开和读取当前文件:
I use the following to open and read in the file currently:
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语句,之后再使用相同的代码,而不是像这样进行复制?我还没有找到一种方法来做到这一点.
Is there a way to assign cin to an ifstream and simply add an else statement if argc > 1 fails, using the same code afterwards instead of duplicating like this? I haven't been able to find a way to do this.
使阅读部分具有其自身的功能.将ifstream
或cin
传递给它.
Make the reading part a function of its own. Pass either an ifstream
or cin
to it.
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.
}