简体   繁体   中英

Why can I not use std::cin.getline() twice in succession?

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().

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' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM