[英]C++ If text file contains specific word or not
如果他/她输入的数据(单词)存在于.txt文件中,我需要可以验证输入的内容。 如果只有一种情况,我的代码将正常工作。
if(line.find("2014-1113") != string::npos)
但是,当我尝试添加else条件时。每次运行程序时,else条件始终是输出。 我不知道为什么
我尝试进行一个实验,以便如果用户输入的txt文件中不存在的单词,将显示输出错误,表明他/她输入的数据有问题。 当我使用调试模式运行时。 这是输出:
cout << "NOT FOUND!";
break;
在运行它之前,即使我更改了单词并且它存在于我的txt文件中,仍然会输出ELSE条件。
有人知道我的问题吗? 谢谢!
这是我的示例txt文件:
2015-1111,Christian Karl,M
2015-1112,Joshua Evans,M
2015-1115,Jean Chloe,F
2015-1113,Shairene Traxe,F
2015-1114,Paul Howard,M
然后我的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream stream1("db.txt");
string line ;
while( std::getline( stream1, line ) )
{
if(line.find("2015-1113") != string::npos){ // WILL SEARCH 2015-1113 in file
cout << line << endl;
}
else{
cout << "NOT FOUND!";
break;
}
}
stream1.close();
system("pause");
return 0;
}
当代码经过第一行时,找不到所需的内容,而是进入else子句。 然后,它打印“找不到”并中断( break
终止while循环)。
您应该按照以下思路进行操作:
bool found = false;
while( std::getline( stream1, line ) && !found)
{
if(line.find("2015-1113") != string::npos){ // WILL SEARCH 2015-1113 in file
cout << line << endl;
found = true;
// If you really want to use "break;" Here will be a nice place to put it. Though it is not really necessary
}
}
if (!found)
cout << "NOT FOUND";
由于if条件在循环内,因此else语句将针对不包含要搜索内容的每一行运行。 您需要做的是使用bool标志并将其设置在循环中。 循环完成后,您可以检查标志并查看是否找到该行。
bool found = false;
while(std::getline(stream1, line) && !found )
{
if(line.find("2015-1113") != string::npos){ // WILL SEARCH 2015-1113 in file
found = true;
}
}
if (found)
std::cout << "Your line was found.";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.