I was learning how to read strings with getline function.
I know that getline function read string as far as we don\'t hit enter or the size value in the getline para
std::istream::getline
is being overloaded with data.
According to cppreference,
Behaves as UnformattedInputFunction. After constructing and checking the sentry object, extracts characters from *this and stores them in successive locations of the array whose first element is pointed to by s, until any of the following occurs (tested in the order shown):
- end of file condition occurs in the input sequence (in which case
setstate(eofbit)
is executed)- the next available character c is the delimiter, as determined by
Traits::eq(c, delim)
. The delimiter is extracted (unlike basic_istream::get()) and counted towards gcount(), but is not stored.count-1
characters have been extracted (in which casesetstate(failbit)
is executed).
Emphasis mine.
cin.getline(line1,7);
// ^ This is count
can read only 6 characters with the 7th reserved for the null terminator. "oranges" is seven characters, and this places cin
in a non-readable error state that must be cleared before reading can be continued. Reading of the second line
cin.getline(line2,7);
instantly fails and no data is read.
The obvious solution is
cin.getline(line1, sizeof(line1));
to take advantage of the whole array. But...
Any IO transaction should be tested for success, so
if (cin.getline(line1, sizeof(line1)))
{
// continue gathering
}
else
{
// handle error
}
is a better option.
Better still would be to use std::getline and std::string to almost eliminate the size constraints.