如何在刷新`std :: cin`的内容之前再读一遍? [英] How do you flush the contents of `std::cin` before an additional read from it?
问题描述
我想多次读取单个字符。抓住的是,我需要防止用户错误。例如:
I am trying to read a single character multiple times. The catch is that I need to prevent user errors. So for example:
char arr[10];
for(int i = 0; i < 10; i++)
{
cin.get(arr[i]);
}
输入应该是 a,b ,c,d,...
。但如果有人要为第一个条目输入 ab
,我想捕获 a
,然后忽略 b
。我知道 cin.ignore
但是我不知道我会忽略任意数量的字母数字字符或符号,因为我想忽略一个潜在的无限数量然后停止忽略并重新读取。
Where the inputs should be something like a, b, c, d, ...
. But if someone were to enter ab
for the first entry I want to capture the a
and then ignore the b
. I know about cin.ignore
however I don't know how I would go about ignoring an arbitrary number of alphanumeric characters or symbols considering that I want to ignore a potentially unlimited number of characters and then stop ignoring and read again.
如何忽略任意数量的字符,然后停止忽略或清除cin的缓冲区。
How can I either ignore an arbitrary number of characters and then stop ignoring or how can I actually flush the buffer for cin.
推荐答案
大多数输入都是换行符,所以如果你想忽略输入流中的所有字符,使用:
Most input is line feed so if you want to ignore all characters in the input stream until you hit a newline then you could use:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
由于我们忽略 streamsize
在输入缓冲区中不应有额外的内容。
Since we ignore up to the streamsize
there should not be an extra content in the input buffer.
这篇关于如何在刷新`std :: cin`的内容之前再读一遍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!