Every time I do a quick snippet of C++ code line
std::string s; cin >> s;
I curse myself because I forgot it stops at the whitespace rather than getting an entire line.
Then, on remembering getline
, I invariably become confused as to the two varieties:
std::string s; getline (std::cin, s);
and:
char cs[256]; std::cin.getline (cs, sizeof (cs));
Is there actually a difference between these two other than the data type?
It seems to me the C++ way should be the former. Under what circumstances would I use the latter, given that I probably should be using real strings instead of null-terminated character arrays anyway?
And, since input should really be the purview of the input streams, why isn't the former part of istream
?
The second method of declaring the C++ getline() function with two parameters is: istream& getline( istream& is, string& str ); In the above syntax, istream& getline is to define the function, and the three parameters are: istream& is: This is an istream class's object to specify the location to read the input stream.
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. Usually, the common practice is to use cin instead of getline.
Programming in C++ – getline() and write() functionsA line of text can be read or display effectively using the line oriented input/output functions getline() and write(). The getline() function reads a whole line of text that ends with a newline character.
The getline() function reads a whole line, and using the newline character transmitted by the Enter key to mark the end of input. The get() function is much like getline() but rather than read and discard the newline character, get() leaves that character in the input queue.
The global getline() function works with C++ std::string objects.
The istream::getline() methods work with "classic" C strings (pointers to char
).
Bear in mind that the Standard library is composed from 3 (main) parts: IOStream, String and STL, plus some tossed in goodies and the C-headers.
I don't see anything weird in having those parts loosely coupled (though I wish it was not the case).
Other incongruities include: std::string::length
vs std::string::size
, the latter having been added for interface compatibility with the STL and the former having been retained for compatibility with older code.
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