user4440884
user4440884

Reputation:

Why it repeats 5 times?

void firstSentence(void){
    string incorrectSentence;
    string correctSentence = "I have bought a new car";
    cout << "Your sentence is: I have buy a new car" << endl;
    cout << "Try to correct it: ";
    cin >> incorrectSentence;
    if(incorrectSentence == correctSentence){
        cout << "Goosh. Your great. You've done it perfectly.";
    }
    else{
        firstSentence();
    }
}

That's my function I am trying to call in my program. But I am stuck little and angry because I can't find solution on my own. What it does is, that if the condition in "if statement" is true, my output is not what I expected. Output is 5 times repeated "Try to correct it. Your sentence is: I have buy a new car ..

Why it repeats exactly 5 times and whatever, what's going on there and why it's not working?

Upvotes: 0

Views: 114

Answers (1)

Wintermute
Wintermute

Reputation: 44063

This:

cin >> incorrectSentence;

does not read a line but a whitespace-delimited token. If your input is the correct sentence, that means that the first time it will read "I", while the rest of the sentence remains in the input stream. The program correctly determines that "I" is not the same as "I have bought a new car", loops, and reads "have" the second time around. This is also not the same as the correct sentence, so it loops again and reads "bought". This continues until everything is read from the stream, at which point cin >> incorrectSentence; blocks again .

The solution is to use

getline(cin, incorrectSentence);

...which reads a line.

Upvotes: 6

Related Questions