Using getline(cin, s) after cin

using getline with cin
read until newline c++
c++ read string with spaces from file
getline not working - c++
how to ignore whitespace in c++
cin c++
c++ getline from file
stdin getline

I need the following program to take the entire line of user input and put it into string names:

cout << "Enter the number: ";
int number;
cin >> number;

cout << "Enter names: ";
string names;

getline(cin, names);

With the cin >> number command before the getline() command however (which I'm guessing is the issue), it won't allow me to input names. Why?

I heard something about a cin.clear() command, but I have no idea how this works or why this is even necessary.

cout << "Enter the number: ";
int number;
if (cin >> number)
{
    // throw away the rest of the line 
    char c;
    while (cin.get(c) && c != '\n')
        if (!std::isspace(c))
        {
            std::cerr << "ERROR unexpected character '" << c << "' found\n";
            exit(EXIT_FAILURE);
        }
    cout << "Enter names: ";
    string name;
    // keep getting lines until EOF (or "bad" e.g. error reading redirected file)...
    while (getline(cin, name))
        ...use name...
}
else
{
    std::cerr << "ERROR reading number\n";
    exit(EXIT_FAILURE);
}

In the code above, this bit...

    char c;
    while (cin.get(c) && c != '\n')
        if (!std::isspace(c))
        {
            std::cerr << "ERROR unexpected character '" << c << "' found\n";
            exit(EXIT_FAILURE);
        }

...checks the rest of the input line after the number contains only whitespace.

Why not just use ignore?

That's pretty verbose, so using ignore on the stream after >> x is an oft-recommended alternative way to discard content through to the next newline, but it risks throwing away non-whitespace content and in doing so, overlooking corrupt data in the file. You may or may not care, depending on whether the file's content's trusted, how important it is to avoid processing corrupt data etc..

So when would you use clear and ignore?

So, std::cin.clear() (and std::cin.igore()) isn't necessary for this, but is useful for removing error state. For example, if you want to give the user many chances to enter a valid number.

int x;
while (std::cout << "Enter a number: " &&
       !(std::cin >> x))
{
    if (std::cin.eof())
    {
        std::cerr << "ERROR unexpected EOF\n";
        exit(EXIT_FAILURE);
    }

    std::cin.clear();  // clear bad/fail/eof flags

    // have to ignore non-numeric character that caused cin >> x to
    // fail or there's no chance of it working next time; for "cin" it's
    // common to remove the entire suspect line and re-prompt the user for
    // input.
    std::cin.ignore(std::numeric_limits<std::streamsize>::max());
}
Can't it be simpler with skipws or similar?

Another simple but half-baked alternative to ignore for your original requirement is using std::skipws to skip any amount of whitespace before reading lines...

if (std::cin >> number >> std::skipws)
{
    while (getline(std::cin, name))
        ...

...but if it gets input like "1E6" (e.g. some scientist trying to input 1,000,000 but C++ only supports that notation for floating point numbers) won't accept that, you'd end up with number set to 1, and E6 read as the first value of name. Separately, if you had a valid number followed by one or more blank lines, those lines would be silently ignored.

Problems with getline(cin, name), A more common usage is cin.ignore() with nothing in parentheses. strings. Consider the following example: string s; char c; getline(cin, s); cout << s << endl;. C++ program to read string using cin.getline() Since cin does not read complete string using spaces, stings terminates as you input space. While cin.getline() – is used to read unformatted string (set of characters) from the standard input device (keyboard). This function reads complete string until a give delimiter or null match.

cout << "Enter the number: ";
int number;
cin >> number;

cin.ignore(256, '\n'); // remaining input characters up to the next newline character
                       // are ignored

cout << "Enter names: ";
string names;
getline(cin, names);

[PDF] C++ Reading a Line of Text, std::getline() can run into problems when used after cin >> var . Reading in numbers directly is problematic; Using getline to input numbers is a more robust  Using cin.getline. The getline member function is similar to the get function. Both functions allow a third argument that specifies the terminating character for input. The default value is the newline character. Both functions reserve one character for the required terminating character.

Another way of doing it is to put a

cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' ); 

after your cin>>number; to flush the input buffer completely (rejecting all of the extra characters until a newline is found). You need to #include <limits> to get the max() method.

Tips and Tricks for Using C++ I/O (input/output), C++ code following #include <iostream> #include <string> using namespace std; string fullName; cout << "Type your full name: "; getline(cin,fullName); cout << "​Your name is: " << fullName; return 0; } Indeed, its >>'s fault. When used immediately after whitespace-delimited input, e.g. after int n; std::cin >> n;, getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with cin.ignore(std::numeric_limits<std::streamsize>::max(), ' '); before switching to line-oriented input.

Try:

int number;

cin >> number;

char firstCharacterOfNames;
cin >> firstCharacterOfNames;  // This will discard all leading white space.
                               // including new-line if there happen to be any.

cin.unget();                   // Put back the first character of the name.

std::string  names;
std::getline(cin, names);      // Read the names;

Alternatively. If you know that number and names will always be on different lines.

cin >> number;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
std::getline(cin, names);

C++ doesnt support getline and cin simultaneously?, extract to string #include <iostream> #include <string> int main () { std::string name; std::cout << "Please, enter your full name: " ; std::getline (std::cin,name);  Using getline(cin, s) after cin. 44. cin and getline skipping input. 19. Need help with getline() 5. cin.getline() is skipping an input in C++. 3. Why is std::getline

You can use std::ws to extract any whitespace characters in the input buffer before using getline. Header for std::ws is sstream.

cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
cin>>ws;
getline(cin, names);

getline (string) - C++ Reference, After each small part, run a few tests to make sure your code works. For example, first Using cin to Input Strings (not as good as getline). You can use cin to  @aizen92, any time you cin >> something, it will leave a newline in the buffer. The buffer remains when you switch functions, as long as you're still using cin. If the next operation to do with cin is getline, it will read that leftover newline and seem to skip getting input. – chris May 11 '12 at 15:02. Here ya go.

Discussion 4-13, cin.getline( name of string , size of the string ); Consider the following example : Suppose that i enter Hello World for both str and strr. #include<iostream> using  The C++ getline() is a standard library function that is used to read a string or a line from an input stream. It is a part of the <string> header . The getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered.

What does cin.getline do in C++?, If a character delimiter is specified, then getline() will use delimiter to decide when to For example, the following code reads a line of text from STDIN and displays it to STDOUT: string s; getline( cin, s ); cout << "You entered " << s << endl;. cin.getline() function allows you to input multiword strings. Multiword means strings that contains white spaces. If you try to input a multiword string using cin only and try to output it using cout You will able to print only first word of the string till first white space.

getline, operator""s When consuming whitespace-delimited input (e.g. int n; std::cin >> n;) any whitespace The following example demonstrates how to use getline function to read user's input and how to process file line by line. Relationship Between getline and cin. getline function accepts cin as a parameter. Difference Between getline and cin Definition. getline() is a standard library function in C++ and is used to read a string or a line from the input stream while cin is an object in C++ of the class istream that accepts input from the standard input device.

Comments
  • Assuming you typed: 5<enter>John<enter>. Then cin >> number reads JUST 5. leaving the new-line (enter) character on the stream. Thus when you try and read the name with getline(cin,name) it reads to the end of line. BUT NOTE there is a new-line character just there ready to be read (thus names will be empty (because you did not read off the new-line character after the 5). If you want to switch between >> and getline() you need to be carefull about trailing end of lines on your input.
  • @LokiAstari: That's a better answer than any of those posted below. Could you post it as such?
  • Erm, this doesn't answer the question or fix the problem. -1
  • @LightnessRacesinOrbit: how does it "not fix the problem"? The first call to getline consumes the newline after the number and loops until it finds a non-empty line... seems fixed to me. The OP's question didn't ask "why?" the problem happened, but did comment that he wasn't sure why clear might be necessary - someone else edited the 5-year-old question 2 days ago to add that, substantially changing the gist.
  • Now you've edited in [someone else's] answer it's better
  • @LightnessRacesinOrbit: I edited in the gist of my comment on jonsca's answer, from 2011 - nothing new.
  • @jonsca: "rejecting all the extra characters" is dubious in most production systems... fine to eat whitespace, but discarding unknown data can easily and silently lead to wrong results.
  • @cnicutar it varies from implementation to implementation
  • @Tony How about instead of a getline, if you have a loop taking in characters positioned after the cin statement? Surely the extra characters will throw a wrench into that. Are you talking more about security holes?
  • "loop taking in characters"... if you mean while (isspace(cin.peek())) cin.ignore()... looks good to me. Re above, I was thinking more of a user misunderstanding the input format requirements, or some script generating the input breaks, but the broken input seem to be processed successfully because it's ignored - they can end up trusting broken results. If input's not to spec, it's better to have your program generate an error.
  • @Tony Ah, okay, I misinterpreted what you were trying to say. Good point about validation.
  • What if it's '\r'? This is a remarkably fragile solution that I would reject in code review.