c++ - 为什么不能连续使用 std::cin.getline() 两次?

标签 c++ istream

只有第一次调用 getline() 时才会从 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 entered:”。它没有让我有机会输入更多文本,也没有显示从之前调用 getline() 时截断的任何字符。

最佳答案

std::cin.getline(line, recordLen+1);

这里,如果输入的长度超过recordLen 个字符,则剩余的字符将不会被读取并保留在流中。下次您从 cin 读取时,您将读取那些剩余的字符。请注意,在这种情况下,cin 将提高其 failbit,这可能就是您遇到的情况。

如果您的第一个输入恰好是 recordLen 个字符长,则只有换行符将保留在流中,而下一次调用 getline 将显示为读取一个空字符串。

除此之外,getline 会覆盖缓冲区。

如果您想忽略同一行中第一个 recordLen 字符之外的任何内容,您可以调用 istream::clear 来清除 failbitistream::ignore 忽略 istream::getline 之后的其余行:

std::cin.getline(line, recordLen+1);
std::cin.clear();
std::cin.ignore( std::numeric_limits<streamsize>::max(), '\n' );

关于c++ - 为什么不能连续使用 std::cin.getline() 两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16393284/

相关文章:

c++ - 在 Windows 上运行 Linux Makefile(.so 文件)

c++ - 为什么快速排序在重复元素多的情况下效率低下?

c++ - 同时迭代和修改 unordered_set?

c++ - 具有弹出功能的 istream

c++ - 为什么我的代码无法识别空行 C++

c++ - 我可以从具有不同数字分隔符的 istream 中读取 double 值吗?

visual-studio-code - 无法在 VS Code 中调试 C++

c++ - 如何放大 'free memory'

c++ - 如何从 std::istream 中读取数据(使用运算符>>)?

c++ - 从 Istream 读取,如何先读一个字再读一整行,然后返回?