Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getline() not working second time in a while loop

Tags:

c++

while-loop

First is the while loop code:

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;
}
}

In this when the loop goes off a second time (press yes) it skips back to:

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

I think it has somewhat to do with providing an answer to getline() early but I don't know where.

I.E:

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:

The intention is to repeat the loop when pressing yes (including being able to enter another command).

like image 408
user1119577 Avatar asked Dec 01 '25 08:12

user1119577


2 Answers

cin >> yes;

Right there, the user enters a letter, let's say 'y'. Then hits enter. This stores 2 characters in the input buffer, 'y' and '\n'. The 'y' gets stored in yes, but the '\n' remains. When you get to here again:

getline (cin, option);

Since there's already a newline character in the buffer, getline has what it's looking for, and doesn't need to prompt the user.

There are a few solutions to this. You could add a call to cin.ignore() after cin >> yes. Or you could make yes a string, and use getline instead of operator>> there.

like image 128
Benjamin Lindley Avatar answered Dec 04 '25 00:12

Benjamin Lindley


If you are taking inputs for different test cases this method works: Put "cin.ignore()" after taking the number of Test cases. Example:-

int main() {
    
    int t;
    cin>>t;
    
    cin.ignore();     //putting of ignore function
    while(t--)
    {
        string str;
        getline(cin,str);
        
        cout<<str<<"\n";
    }
}
like image 21
Shashi Avatar answered Dec 04 '25 01:12

Shashi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!