4

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.

Yang
  • 6,872
  • 7
  • 44
  • 62
  • Prefer `while (getline(infile,tweet))` to `while (!infile.eof()){ getline(infile,tweet);` [Reasoning](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). TL;DR version: 1) testing for EOF only catches EOF. Many things can co wrong while reading and you want to check pretty much all of them. 2) Testing for correctness BEFORE reading allows the subsequent read to fail unchecked. What you need to do is Read data. Check that data was read. Use data. `while (getline(...))` reads and checks, only entering the loop if `getline` succeeded. – user4581301 Jan 31 '19 at 05:28

2 Answers2

3

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) {
Hanjoung Lee
  • 1,923
  • 1
  • 9
  • 16
1

The correct usage is shown below:

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

Please refer to the correct usage here.

Akash C.A
  • 160
  • 9