Difference between cin and cin.get() for char array

Ruben P picture Ruben P · Apr 14, 2015 · Viewed 64k times · Source

I have these 2 codes:

char a[256];
cin>>a;
cout<<a;

and

char a[256];
cin.get(a,256);cin.get();
cout<<a;

and maybe, relative to the second one without cin.get();

char a[256];
cin.get(a,256);
cout<<a;

My question is (first one) : for a char array, what should i use? cin or cin.get()? And why should i use cin.get(); with no parameter after my char initialisation?

And my second question is: my c++ teacher taught me to use every time cin.get() for initialisation chars and AFTER every initialisation char array or int array or just int or whatever, to again put cin.get(); after it. That's what i wanted to ask initially.

So, now i got these 2: In this case, without cin.get() after the integer initialisation, my program will break and i can't do anymore my char initialisation.

int n;
cin>>n;
char a[256];
cin.get(a,256); cin.get();  // with or without cin.get();?
cout<<a;

And the correct one:

int n;
cin>>n; cin.get();
char a[256];
cin.get(a,256); cin.get(); // again, with or without?
cout<<a;

So, what's the matter? Please someone explain for every case ! Thank you.

Answer

Mike Seymour picture Mike Seymour · Apr 14, 2015

They do different things, so choose whichever does what you want, or the better alternatives given below.

The first cin>>a; reads a single word, skipping over any leading space characters, and stopping when it encounters a space character (which includes the end of the line).

The second cin.get(a,256);cin.get(); reads a whole line, then consumes the end-of-line character so that repeating this will read the next line. cin.getline(a,256) is a slightly neater way to do this.

The third cin.get(a,256) reads a whole line but leaves the end-of-line character in the stream, so that repeating this will give no more input.

In each case, you'll get some kind of ill behaviour if the input word/line is longer than the fixed-size buffer. For that reason, you should usually use a friendlier string type:

std::string a;
std::cin >> a;              // single word
std::getline(std::cin, a);  // whole line

The string will grow to accommodate any amount of input.