当前位置: 动力学知识库 > 问答 > 编程问答 >

C++ If text file contains specific word or not

问题描述:

I need something that validates input if his/her inputted data (word) exists in .txt file. My code is working if there is just a one condition.

if(line.find("2014-1113") != string::npos)

But when I try to add else condition.. Everytime I run the program, the else condition is always the output. I don't know why..

I try to have a experiment so that if user enter a word that is not exist in my txt file, there will be an output that something is wrong with his/her inputted data. When I run at using debugging mode. This is the output:

 cout << "NOT FOUND!";

break;

Until I run it, even I change the word and it exist on my txt file, still the ELSE condition is the output..

Does anyone knows my problem? thanks!

Here is my sample txt file:

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

Then my code:

#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;

}

网友答案:

When your code goes over the first line, it doesn't find what it's looking for, and goes into the else clause. Then it prints "NOT FOUND" and break (the break stops the while loop).

What you should do is something along these lines:

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";
网友答案:

Since your if condition is inside you loop the else statement will run for every line that does not contain what you are searching for. What you need to do is use a bool flag and set that in the loop. After the loop finishes then you check the flag and see if the line was found or not.

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.";
分享给朋友:
您可能感兴趣的文章:
随机阅读: