Reputation: 11503
Only the first call to getline()
appears to read anything in from std::cin
. Is the fact that buffer
contains something a problem - why doesn't getline()
just overwrite the contents of buffer
?
How can I get the second call to getline()
to read something in?
My code:
const int recordLen = 20;
// truncate the input to 20 chars
void getText(char line[])
{
std::cout << "Enter something for getText: ";
std::cin.getline(line, recordLen+1);
for(int i = std::strlen(line); i < recordLen; i++)
{
line[i] = ' ';
}
line[recordLen] = '\0';
}
int main()
{
char buffer[340];
getText(buffer);
std::cout << buffer;
std::cout << "Now enter some more text:";
// put more text into buffer
std::cin.getline(buffer, 30);
std::cout << "you entered : " << buffer << std::endl;
return 0;
}
So - example output of program:
Enter something for getText: alskdjfalkjsdfljasldkfjlaksjdf alskdjfalkjsdfljasldNow enter some more text:you entered :
After the display of "Now enter some more text:", the program immediately displays "you entered:". It does not give me the opportunity to enter more text, neither does it display any characters that were truncated from the previous call to getline().
Upvotes: 3
Views: 5082
Reputation: 7848
std::cin.getline(line, recordLen+1);
Here, if the input is longer than recordLen
chars, the remaining characters will not be read and will remain in the stream. The next time you read from cin
, you'll read those remaining characters. Note that, in this case, cin
will raise its failbit
, which is probably what you're experiencing.
If your first input is exactly recordLen
chars long, only the newline will remain in the stream and the next call to getline
will appear to read an empty string.
Other than that, getline
does overwrite the buffer.
If you want to ignore anything beyond the first recordLen
chars on the same line, you can call istream::clear
to clear the failbit
and istream::ignore
to ignore the rest of the line, after istream::getline
:
std::cin.getline(line, recordLen+1);
std::cin.clear();
std::cin.ignore( std::numeric_limits<streamsize>::max(), '\n' );
Upvotes: 11