为什么它重复 5 次

Why it repeats 5 times?

本文关键字:为什么      更新时间:2023-10-16
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();
    }
}

这是我尝试在我的程序中调用的函数。但是我被困住了,很生气,因为我自己找不到解决方案。它的作用是,如果"if 语句"中的条件为真,则我的输出不是我预期的。输出重复 5 次"尝试纠正它。你的句子是:我买了一辆新车..

为什么它

正好重复 5 次等等,那里发生了什么,为什么它不起作用?

这个:

cin >> incorrectSentence;

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

解决方案是使用

getline(cin, incorrectSentence);

。读一行。