Team. Coco Team. Coco - 3 months ago 8
C++ Question

Why does this while Loop never end?

So I feel that I am close to solving a programming assignment that takes the most used word of each line and prints it on a line. So for example:

I am a man, am right?
I don't know if i like that.
It's okay to not feel okay.


Would print: "am i okay" (punctuations and case are ignored for the assignment)

This is what I have done so far, but the problem is that the while loop that scans the lines is never broken and thus never prints the output in the external for loop. Anybody see where I went wrong?

string line;
vector<string> result;
while(getline(cin,line)){ //on each line

}

Answer

Currently your program is waiting for an EOF character which indicates the input has ended. If you are running this and entering the input from the command line, you can manually insert an EOF by pressing Ctrl+D on *nix, or Ctrl+Z on windows. This will cause your program to break out of your getline loop.

If you would rather not do that, you need a way to break out of the getline loop, otherwise it will continue to run in that loop.

A nice idea might be detecting an empty line, so pressing enter twice ends the loop:

while(getline(cin,line)){     //on each line
    if(line == "")
        break;
    ...
}