C++ C++;文本文件是否包含特定单词

C++ C++;文本文件是否包含特定单词,c++,C++,我需要的东西,验证输入,如果他/她的输入数据(字)存在于.txt文件。如果只有一个条件,我的代码就可以工作 if(line.find("2014-1113") != string::npos) 但当我尝试添加其他条件时。。每次我运行程序时,else条件总是输出。我不知道为什么 我试着做一个实验,如果用户输入了我的txt文件中不存在的单词,就会有一个输出,表明他/她输入的数据有问题。当我使用调试模式运行时。这是输出: cout << "NOT FOUND!"; bre

我需要的东西,验证输入,如果他/她的输入数据(字)存在于.txt文件。如果只有一个条件,我的代码就可以工作

if(line.find("2014-1113") != string::npos)
但当我尝试添加其他条件时。。每次我运行程序时,else条件总是输出。我不知道为什么

我试着做一个实验,如果用户输入了我的txt文件中不存在的单词,就会有一个输出,表明他/她输入的数据有问题。当我使用调试模式运行时。这是输出:

    cout << "NOT FOUND!";
    break;
然后我的代码:

#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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
ifstream stream1(“db.txt”);
弦线;
while(std::getline(stream1,line))
{
如果(line.find(“2015-1113”)!=string::npos){//将在文件中搜索2015-1113

cout当代码越过第一行时,它找不到它要查找的内容,进入else子句。然后它打印“NOT FOUND”并中断(
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";
boolfound=false;
while(std::getline(stream1,line)&&&!found)
{
如果(line.find(“2015-1113”)!=string::npos){//将在文件中搜索2015-1113

cout由于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.";
boolfound=false;
while(std::getline(stream1,line)&&&!found)
{
如果(line.find(“2015-1113”)!=string::npos){//将在文件中搜索2015-1113
发现=真;
}
}
如果(找到)

std::cout,这是您应该发布的MCVE:为什么输出仍然显示“NOT FOUND!”而不是显示单词所在的行?因为循环永远不会走那么远。您在第一行(不匹配)中断。如果
,他可能想中断
。这取决于。
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.";