3

只有第一次调用 togetline()似乎会读取 from 中的任何内容std::cin。包含某些东西的事实是否buffer有问题 - 为什么不getline()只是覆盖 的内容buffer

我怎样才能得到第二个电话getline()来读一些东西?

我的代码:

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;
}

所以 - 程序的示例输出:

为 getText 输入一些内容:alskdjfalkjsdfljasldkfjlaksjdf alskdjfalkjsdfljasld 现在输入更多文本:您输入了:

在显示“Now enter some more text:”后,程序立即显示“you enter:”。它没有让我有机会输入更多文本,也没有显示从上一次调用 getline() 中截断的任何字符。

4

1 回答 1

11
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' );
于 2013-05-06T06:51:58.593 回答