Search code examples
c++inputiostreamgetline

why do two getline() lead to no input?


I am creating a simple login program.

#include <iostream>
#include <string>
using namespace std;    

void showRegister()
{
    string user;
    string pw;
    cout << "Enter your username:";
    getline(cin, user);
    cout << "Enter your password:";
    getline(cin, pw);
    cout << "You have successfully registered!" << endl;
    writeIntoFile(user, pw);
    showMenu();
}
void showMenu() {
    int select;
    do {
        cout << "1. Register"<<endl;
        cout << "2. Login" << endl;
        cout << "3. Exit" << endl;
        cout << "Enter your choice: ";
        cin >> select;
    } while (select > 3);

    switch (select)
    {
    case 1:
        showRegister();
        break;
    case 2:
        showLogin();
        break;
    case 3:
    default:
        break;
    }
}

int main()
{
    showMenu();
    return 0;
}

This is the result when I choose 1: enter image description here

As you see, I can not enter username. In function showRegister(), when I add cin.ignore() before getline(cin, user), this is the result: enter image description here

As I understand, getline() reads a line until it reaches character \n and skip the rest. So why in this case, two successive getline() commands (getline(cin, user) and getline(cin, pw) lead to the fact that I can not enter username?


Solution

  • The fact is getline takes input from buffer if something exists in buffer else it ask the user for value. What actually happens in your code is as soon as you enter value for select which is not greater than 3 it comes out of the loop after with a value you entered for select and the entered (which stands for \n) that you pressed get stored in buffer. So know when you come to getline for user it sees '\n' from the buffer as getline first check in buffer, so it skip the value insertion and buffer gets emptied and now when you come to getline that is used for password it ask the user for password as buffer was empty.