I run this piece of code on Visual C++ 2010
char c[10];
cin.get(&c[0],5);
cin.get(&c[2],4);
cout << c << endl;
and if I feed “123456789” to cin, the cout clause will print “12567”, which is the result I expected.
But if I write:
char c[10];
cin.getline(&c[0],5);
cin.getline(&c[2],4);
cout<< c <<endl;
and feed the same string, it will only show me “12”, where c=={‘1′,’2′,’\0′,’4′,’\0’}
According to the documentation, the difference between cin.get and cin.getline is that cin.get does not discard the delim character as cin.getline does, so I don’t know why this happens. Can anyone give me hints?
What is happening is that if
basic_iostream::getline()reaches the limit of characters to be read (thestreamsizeargument minus 1), it stops reading then places a null character after the data it has read so far. It also sets thefailbiton the stream.So assuming that the stream has
"123456789"ready to read, when you callcin.get(&c[0],5)the array will get{'1','2','3','4','\0'}placed into elements0through4. And thefailbitis set on the stream.Now when you call
cin.get(&c[2],4), thefailbitis set on the stream, so nothing is read. Thegetline()call does nothing but place the terminating null into the array at index2(even if nothing is read from the stream,getline()will place the null character – even if the non–read is because of thefailbit). So the array now looks like:The documentation you link to mentions this:
But
getline()does a lot, so it’s easy to miss that detail.