Search code examples
c++stringstduser-inputgetline

How do I get user inputs for a string and then an int?


I have a database class that is an array that will hold a number of objects. The function will take a couple of inputs from the user which include both strings and ints

For example:

std::cout << "Enter first name: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, first_name);
std::cout << "Enter last name: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, last_name);
std::cout << "Enter age: ";
std::cin >> age;

When I run the code, after I hit enter after entering the last name, it just starts a new line and I have to enter another input before it asks for the age input.

I heard it was bad to mix getline and cin, and that it's better to use one or the other. What can I do to make this work and what would be good practice moving forward?

Edit: I added in the ignores when I initially searched for solutions because without them, the code wouldn't bother waiting for user input. The output would be "Enter first name: Enter last name: "

Edit2: RESOLVED. Problem was I had used "cin >>" earlier in my code for user to input an int variable and needed the first cin.ignore statement, but not the other. Did not include that part of the code because I didn't know that was affecting it. Still new to all this so thanks everyone for their help!


Solution

  • According to the documentation of std::basic_istream::ignore(), this function behaves as an Unformatted Input Function which mean it is going to block and wait for user input if there is nothing to skip in the buffer.

    In your case both of your ignore statments are not neccessary since std::getline() will not leave the new line character in the buffer. So what is actually happening is:

    std::cout << "Enter first name: ";
    /*your first input is skipped by the next ignore line because its going to block until
    input is provided since there is nothing to skip in the buffer*/
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    /* the next getline waits for input, reads a line from the buffer and also removes the 
    new line character from the buffer*/
    std::getline(std::cin, first_name);
    
    std::cout << "Enter last name: ";
    /*your second input is skipped by the next ignore line because its going to block until
    input is provided since there is nothing to skip in the buffer*/
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    /* the next getline waits for input and this is why it seems you need to provide 
    another input before it ask you to enter the age*/
    std::getline(std::cin, last_name);
    

    You need to remove the ignore statments to make this work. You may also want to read When and why do I need to use cin.ignore() in C++