[英]How to use getline to print the correct line from txt file
I'm trying to create a program that will search a given directory txt file for a certain string.我正在尝试创建一个程序,该程序将在给定的目录 txt 文件中搜索某个字符串。 Once that string is found, the program will print onto the screen the information only on that line within the txt file.
找到该字符串后,程序将仅将 txt 文件中该行的信息打印到屏幕上。 My code is able to check and see if the string is inside the file, but instead of printing only the line it's contained in, it prints everything but the line I want.
我的代码能够检查并查看字符串是否在文件中,但它不是只打印它包含的行,而是打印除我想要的行之外的所有内容。
while(!inF.eof()){
getline(inF, hold);
if(hold.find(crnS)){
isFound = 1;
cout << hold << endl;
}
}
There are two problems with your code:您的代码有两个问题:
see Why is iostream::eof inside a loop condition (ie `while (!stream.eof())`) considered wrong?请参阅为什么 iostream::eof 在循环条件(即`while (!stream.eof())`)中被认为是错误的?
std::string::find()
returns an index, not a bool
. std::string::find()
返回一个索引,而不是一个bool
。 Any non-zero value is evaluated as true, so any return value other than index 0 will satisfy your if
statement, including std::string::npos
(-1) if find()
does not find a match.任何非零值都被评估为真,因此索引 0以外的任何返回值都将满足您的
if
语句,包括std::string::npos
(-1) 如果find()
未找到匹配项。 That means your code outputs each line where crnS
is found anywhere other than at very beginning of the line, as well as when crnS
is not found at all.这意味着你的代码输出,其中每行
crnS
发现比在最开始的路线,以及在其他任何地方crnS
都找不到。
Use this instead:改用这个:
while (getline(inF, hold)) {
if (hold.find(crnS) != string::npos) {
isFound = 1;
cout << hold << endl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.