如何使用 getline 从 txt 文件打印正确的行
How to use getline to print the correct line from txt file
我正在尝试创建一个程序,该程序将在给定目录 txt 文件中搜索特定字符串。找到该字符串后,程序将仅在屏幕上打印 txt 文件中该行的信息。我的代码能够检查并查看字符串是否在文件中,但它不是只打印它所在的行,而是打印除我想要的行之外的所有内容。
while(!inF.eof()){
getline(inF, hold);
if(hold.find(crnS)){
isFound = 1;
cout << hold << endl;
}
}
您的代码有两个问题:
见Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
std::string::find()
return 是一个索引,而不是 bool
。任何非零值都被评估为真,因此除 索引 0 之外的任何 return 值 都将满足您的 if
语句,包括 std::string::npos
(- 1) 如果 find()
没有找到匹配项。这意味着您的代码输出每一行,其中 crnS
位于行首 除了 之外的任何地方,以及根本没有找到 crnS
的地方。
改用这个:
while (getline(inF, hold)) {
if (hold.find(crnS) != string::npos) {
isFound = 1;
cout << hold << endl;
}
}
我正在尝试创建一个程序,该程序将在给定目录 txt 文件中搜索特定字符串。找到该字符串后,程序将仅在屏幕上打印 txt 文件中该行的信息。我的代码能够检查并查看字符串是否在文件中,但它不是只打印它所在的行,而是打印除我想要的行之外的所有内容。
while(!inF.eof()){
getline(inF, hold);
if(hold.find(crnS)){
isFound = 1;
cout << hold << endl;
}
}
您的代码有两个问题:
见Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
std::string::find()
return 是一个索引,而不是bool
。任何非零值都被评估为真,因此除 索引 0 之外的任何 return 值 都将满足您的if
语句,包括std::string::npos
(- 1) 如果find()
没有找到匹配项。这意味着您的代码输出每一行,其中crnS
位于行首 除了 之外的任何地方,以及根本没有找到crnS
的地方。
改用这个:
while (getline(inF, hold)) {
if (hold.find(crnS) != string::npos) {
isFound = 1;
cout << hold << endl;
}
}