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

时间:2014-11-07 16:40:30

标签: c++

我正在完成一项学校任务,现在正试着弄清楚为什么我的程序没有按照我的意愿行事!

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有一些我不明白的东西,但我还没有通过我的谷歌搜索找到它。有任何帮助吗?

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

1 个答案:

答案 0 :(得分:5)

这是因为用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]));