getline() 在 while 循环中第二次不起作用
getline() not working second time in a while loop
首先是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:
目的是在按 yes 时重复循环(包括能够输入另一个命令(。
cin >> yes;
在那里,用户输入一个字母,让我们说"y"。 然后按回车键。 这会在输入缓冲区中存储 2 个字符,即"y"和""。 "y"存储在 yes 中,但""保留。 当你再次到达这里时:
getline (cin, option);
由于缓冲区中已经有一个换行符,getline 具有它要查找的内容,并且不需要提示用户。
对此有几种解决方案。 您可以在cin >> yes
之后添加对cin.ignore()
的调用。 或者你可以yes
做一个字符串,并使用getline
而不是operator>>
。
如果你正在为不同的测试用例输入,这种方法有效:在获取测试用例的数量后放置"cin.ignore(("。例:-
int main() {
int t;
cin>>t;
cin.ignore(); //putting of ignore function
while(t--)
{
string str;
getline(cin,str);
cout<<str<<"n";
}
}
n
在第一次cin
后将保留在缓冲区中。您可以通过在两次连续读取之间添加空cin.get()
来解决此问题。只需放置一个计数器,并进行第一次验证:
//(...)
int count = 0;
//(...)
while (yes == 'y')
{
if (count == 0)
{
// "Clear the very first input"
cin.get();
}
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;
// Increment the counter
count++;
}
字体:
无法从 cin.get(( 获取
字符http://www.cplusplus.com/reference/istream/istream/get/
有时是cin。Clear(( 或只是 cin.ignore(( 不起作用。我没有研究为什么,但我找到了另一个答案。据我了解,缓冲区中仍有导致这种情况的因素。就像其他海报中所说的那样...
cin.ignore(cin.rdbuf()->in_avail(),'n');
将解决问题。在提出第一个问题后,将这行代码放在您的第一个 getline 语句之前。
http://www.cplusplus.com/forum/beginner/20206/
问题是 cin 在 getline(( 调用读取的流中留下了一个换行符。
尝试在 cin 后添加 cin.ignore(1,''(; 以删除该换行符。 :)
cin.clear(( 在 getline 之后。 它对我有用。
- 为什么 zlib 放气初始化调用一次不起作用?
- (C++)虽然循环一次不起作用,但我引入了多个变量
- 比较字符串的 GetLine 工作一次,然后比较之后不起作用
- 为什么在我的程序中的第二个循环时,当它在循环之前循环时不起作用
- 将列表元素移动到列表末尾的函数多次不起作用
- 虽然循环在第二个循环上不起作用
- gets() 在第一次循环迭代中不起作用,但在后续迭代中工作
- 为什么第一个程序不起作用,而第二个程序有效?其次,为什么输出是它给出的
- C++:一次阅读一个字符,直到一行的末尾不起作用
- 警告:条件的第二个/第三个操作数不起作用 [-Wunused-value]
- QWebPage在第一次加载后不起作用
- 将消息发布到隐藏表单第一次不起作用
- 当我超过第一个 getline() 的输入中的数组大小时,第二个 getline 或其他输入函数不起作用
- 在循环重复两次之前,break 语句不起作用
- getline() 在 while 循环中第二次不起作用
- 为什么 SearchBack 中的 if (find == A[i]) 除了第一次之外没有给出 true?在调试时,除了第一次之外显然不起作用
- 功能删除在我第二次激活它时不起作用
- 第二个参数=0 的 eventfd_write() 不起作用?
- 如果其他以及 >=(2 次)编译良好但不起作用
- 连续两次读取套接字,第二次读取不起作用