gpt4 book ai didi

c++ - getline() 在 while 循环中第二次不工作

转载 作者:太空狗 更新时间:2023-10-29 23:37:15 26 4
gpt4 key购买 nike

首先是while循环代码:

void Menu() {
string option;
char yes;
yes='y';
while (yes == 'y') {
cout << "Commands: buy, sell, directory, and exit: ";
getline (cin, option);
if (option == "buy") {
...
}
...
cout << "Do you wish to continue? Press y for yes, n for no: ";
cin >> yes;
}
}

在此循环第二次结束时(按是)它跳回到:

cout << "Do you wish to continue? Press y for yes, n for no: ";

我认为这与尽早为 getline() 提供答案有关,但我不知道在哪里。

即:

Here is the menu: Commands: buy, sell, directory, and exit: buy
Enter a player's I.D: 2
Here is your current money after purchasing Player X: 150000
Do you wish to continue? Press y for yes, n for no: y
Commands: buy, sell, directory, and exit: Do you wish to continue? Press y for yes, n for no: y
Commands: buy, sell, directory, and exit: Do you wish to continue? Press y for yes, n for no:

目的是在按"is"时重复循环(包括能够输入另一个命令)。

最佳答案

cin >> yes;

就在那里,用户输入了一个字母,比方说“y”。然后点击进入。这在输入缓冲区中存储了 2 个字符,'y' 和 '\n'。 'y' 存储在 yes 中,但 '\n' 保留。当你再次来到这里时:

getline (cin, option);

因为缓冲区中已经有一个换行符,getline 有它要找的东西,不需要提示用户。

对此有一些解决方案。您可以在 cin >> yes 之后添加对 cin.ignore() 的调用。或者您可以使 yes 成为一个字符串,并在那里使用 getline 而不是 operator>>

关于c++ - getline() 在 while 循环中第二次不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8686412/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com