Paul Roscoe
Paul Roscoe

Reputation: 71

How to get a specific word and line from a body of a text file in c++

When running this block of code, the whole file is outputted when I just want the specific line that includes the word. e.g looking for the word paris and displaying all lines instead of specific ones.

I have already tried get line, tweet, but that isn't working, I feel this is part of the problem but i'm not sure.

void choice1() {
    string tweet;
    ifstream infile;
    infile.open("sampleTweets.csv");

    if (infile.good()) {
        while (!infile.eof()) {
            getline(infile,tweet);
            if (tweet.find("Paris") != tweet.length()) {
                cout << "Found Paris in the line" << tweet << endl;
            }
        }
    }
}

Would like it to output the lines that contain that word not all of the lines in the file, but at the moment it is just repeating the text o every line as if the word had been found.

Upvotes: 4

Views: 738

Answers (2)

Akash C.A
Akash C.A

Reputation: 330

The correct usage is shown below:

if (tweet.find("Paris") != std::string::npos) {
}

Please refer to the correct usage here.

Upvotes: 1

Hanjoung Lee
Hanjoung Lee

Reputation: 2152

The standard says find method returns npos if not found. You may refer this.

So the condition line should be:

            if (tweet.find("Paris") != string::npos) {

Upvotes: 3

Related Questions