I have the following code:
char myText[256];
cin.getline(myText,256);
Why exactly do I have to pass a character array to cin.getline() and not a string?
I have read that in general it is better to use strings than character arrays. Should I then convert a character array to a string after retrieving input with cin.getline()
, if that is possible?
getline() Function and Character Array in C++ It is a part of the <string> header. The getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered. Must read the article getline(string) in C++ for more details.
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.
The C++ getline() is a standard library function that is used to read a string or a line from an input stream. It is a part of the <string> header. The getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered.
If you need to take an character array as input you should use scanf("%s",name), printf("%s",name); rather than using the %c . The %c returns the pointer to a character which cannn't be stored in pointer to character array.
You are using the member method of istream. In this case cin. This function's details can be found here :
http://en.cppreference.com/w/cpp/io/basic_istream/getline
However you could use std::getline
Which uses a string instead of a char array. It's easier to use string since they know their sizes, they auto grow etc. and you don't have to worry about the null terminating character and so on. Also it is possible to convert a char array to a string by using the appropriate string contructor.
That's an unfortunate historical artifact, I believe.
You can however, use the std::getline
free function instead.
std::string myText;
std::getline(std::cin,myText);
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