getline() 在 while 循环中第二次不起作用

getline() not working second time in a while loop

本文关键字:第二次 不起作用 循环 while getline      更新时间:2023-10-16

首先是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 之后。 它对我有用。