为什么重复5次?

时间:2015-01-10 21:00:55

标签: c++ string while-loop

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();
    }
}

这是我试图在我的程序中调用的函数。但是我很生气,因为我无法自己找到解决办法。它的作用是,如果条件是&#34; if语句&#34;是的,我的输出不是我的预期。输出重复5次&#34;尝试纠正它。你的判决是:我买了一辆新车..

为什么它会重复5次,无论是什么,在那里发生了什么以及它为什么不起作用?

1 个答案:

答案 0 :(得分:6)

此:

cin >> incorrectSentence;

不读取一行,而是以空格分隔的标记。如果您的输入是正确的句子,则表示第一次读取"I",而句子的其余部分仍保留在输入流中。该程序正确地确定"I""I have bought a new car"不同,循环,并且第二次读取"have"。这也与正确的句子不同,因此它再次循环并读取"bought"。这一直持续到从流中读取所有内容,此时cin >> incorrectSentence;再次阻塞。

解决方案是使用

getline(cin, incorrectSentence);

...读取一行。

相关问题