涉及getline()和循环的C++问题

C++ problems involving getline() and a loop

本文关键字:C++ 问题 循环 getline 涉及      更新时间:2023-10-16

我正在做一项学校作业,现在我正把头撞在墙上,试图弄清楚为什么我的程序没有像我希望的那样运行!

int main(){
    string input;
    char choice;
    bool getChoice(char);
    string getInput();
    CharConverter newInput; 
    do{
        cout << "Please enter a sentence.n";
        getline(cin, input);
        cout << newInput.properWords(input) << endl;
        cout << newInput.uppercase(input) << endl;
        cout << "Would you like to do that again?n";
        cin >> choice;

    } while (getChoice(choice) == true);
    return 0;
}

这个程序在第一轮中运行良好,但当getChoice()==true时,我遇到了一个问题,do-while块第二次循环。在第二个循环中,程序要求我再次输入一个句子,但随后跳到"你想再输入一次吗?",而不允许用户输入或输出properWords()和uppercase()函数的结果。我怀疑getline有一些我不理解的地方,但我还没有通过谷歌搜索找到它。有人帮忙吗?

编辑:我原来的解释有一个错误。

这是因为用getline读取输入与逐字符读取输入不能很好地混合。当您输入Y/N字符以指示是否要继续时,也可以按enter。这会将n放入输入缓冲区,但>>不会从中获取它。当您调用getline时,n就在那里,所以函数会立即返回一个空字符串。

要解决此问题,请将choice设为std::string,使用getline读取它,并将第一个字符发送给getChoice函数,如下所示:

string choice;
...
do {
    ...
    do {
        getline(cin, choice);
    } while (choice.size() == 0);
} while (getChoice(choice[0]));