Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using getline(cin, s) after cin [duplicate]

Tags:

c++

getline

cin

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.

like image 264
pauliwago Avatar asked Apr 21 '11 05:04

pauliwago


People also ask

Can you use Getline after CIN?

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.

Why do we use Getline instead of CIN?

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.

Does Getline ignore newline?

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.

Do you need CIN ignore after Getline?

You don't need to use cin. ignore() with getline() . here is the code prior to the trouble... name2 should be an std::string.


2 Answers

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); 
like image 147
Cristiano Miranda Avatar answered Sep 20 '22 04:09

Cristiano Miranda


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.

like image 31
jonsca Avatar answered Sep 20 '22 04:09

jonsca