【发布时间】:2018-03-13 01:08:50
【问题描述】:
我正在查看this 的帖子和其他一些帖子。如果在输入缓冲区已经为空时调用 ignore() 会发生什么?我在下面的代码中观察到,如果在缓冲区已经为空时调用 ignore(),它将不起作用并等待首先输入某个字符。
int main(void)
{
char myStr[50];
cin.ignore (std::numeric_limits<std::streamsize>::max(),'\n');
cout<<"Enter the String\n";
cin>>myStr;
// After reading remove unwanted characters from the buffer
// so that next read is not affected
cin.ignore (std::numeric_limits<std::streamsize>::max(),'\n');
}
cin.clear() 在ignore() 之后如果缓冲区看起来已经是空的,则会产生进一步的问题。我想在 cin() 之后清除缓冲区是安全的。但是如果我不知道输入缓冲区的状态并且即使它已经是空的我也会清除呢?我是否必须先使用 cin.fail() 或类似的方法检查输入缓冲区是否为空?
其次,cin 本身可能不安全,因为不允许使用空间。所以 getline() 是由一些 SO 帖子建议的,如给定的here。但是 getline() 是否也需要清除输入缓冲区或者它总是安全的?下面的代码是否可以正常工作(现在可以正常工作,但现在确定它是否是安全代码)。
void getString(string& str)
{
do
{
cout<<"Enter the String: ";
getline(std::cin,str);
} while (str.empty());
}
其他 SO 参考: Ref 3
【问题讨论】:
标签: c++ inputstream