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.
The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.
Both getline and cin help to obtain user inputs. The main difference between getline and cin is that getline is a standard library function in the string header file while cin is an instance of istream class. In breif, getline is a function while cin is an object.
In the line “cin >> c” we input the letter 'Z' into variable c. However, the newline when we hit the carriage return is left in the input stream. If we use another cin, this newline is considered whitespace and is ignored. However, if we use getline, this is not ignored.
You don't need to use cin. ignore() with getline() . here is the code prior to the trouble... name2 should be an std::string.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With