gpt4 book ai didi

c++ - 从文本文件或标准输入中读取

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:36 25 4
gpt4 key购买 nike

我有一个基本上读取文本文件并计算每行中每个单词出现次数的程序。使用 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;
}

有没有办法将 cin 分配给 ifstream 并在 argc > 1 失败时简单地添加一个 else 语句,之后使用相同的代码而不是像这样重复?我一直无法找到执行此操作的方法。

最佳答案

让阅读部分成为自己的一个功能。将 ifstreamcin 传递给它。

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.
}

关于c++ - 从文本文件或标准输入中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23050273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com