Need help with getline() [duplicate]

The getline(cin, str); reads the newline that comes after the number read previously, and immediately returns with this "line". To avoid this you can skip whitespace with std::ws before reading the name:

cout << "Enter number:";
cin >> number;
cout << "Enter name:";
ws(cin);
getline(cin, str);
...

Note that this also skips leading whitespace after the newline, so str will not start with spaces, even if the user did input them. But in this case that's probably a feature, not a bug...


Try

cout << "Enter name:";
cin.ignore();
getline(cin, str);

It looks like you want line based reading. For this you probably want to use getline consistently and then parse each line if you need to parse a number from then read line. It makes the input reading more consistent.

This way you don't have to manually scan for the end of each line to guarantee that the next read operation starts on a fresh line.

It also makes adding error handling for repeating input requests simpler.

e.g.

#include <string>
#include <iostream>
#include <istream>
#include <ostream>
#include <sstream>

int parse_integer(const std::string& input)
{
    std::istringstream iss(input);
    int result;
    if (!(iss >> result))
    {
        // error - throw something?
    }
    return result;
}

int main()
{
    int number;
    std::string str;
    int accountNumber;

    std::string inputline;

    std::cout << "Enter number: ";

    if (!std::getline(std::cin, inputline))
    {
        // error - throw something?
    }

    number = parse_integer(inputline);

    std::cout << "Enter name:";

    if (!std::getline(std::cin, inputline))
    {
        // error - throw something?
    }

    str = inputline;

    std::cout << "Enter account number:";

    if (!std::getline(std::cin, inputline))
    {
        // error - throw something?
    }

    accountNumber = parse_integer(inputline);

    return 0;
}

cin >> number

only grabs the numbers from the buffer, it leaves the "enter" in the buffer, which is then immediately grabbed up by the getline and interpreted as an empty string (or string with just the new line, i forget).


cin >> number // eat the numeric characters
getline(cin, str) // eat the remaining newline