执行cin后计算标准输入中的字符数 [英] Counting the number of characters in standard input after a cin has been executed
问题描述
我有一些基本看起来像这样的代码
I have some code that basically looks like this
int a;
cin>>a;
if(!cin.good())
{
std::cin.clear();
std::cin.ignore(2);
// set some default value for 'a' and display some messages
}
如果我给出一个整数(如预期的那样),或者如果我尝试弄乱它并给出最多2个字符,这将很好地工作。例如。 'ss',但是如果我给3个字符输入'sss',则最后一个's'不会被忽略,并被接受作为我程序中的其他cin的输入。
this works fine if I give an integer (as expected) or if I try to mess with it a little and give upto 2 chars. eg. 'ss' , but if I give a 3 char input 'sss' , the last 's' is not ignored and is accepted as the input for some more cin's that I have in my program down the line.
第一个cin发生后,有什么方法可以计数标准输入(缓冲区吗?)中的字符数,所以我可以放心地忽略所有这些字符。
Is there any way to count the number of characters in the standard input (buffers?) after the first cin has happened, so I can safely ignore all of them.
推荐答案
这是如何工作的?它应该忽略输入缓冲区中所有可用的内容,以防止以后消耗第三个 s
。它使用 std :: basic_streambuf :: in_avail
。
How does this work? It should ignore everything available in the input buffer, preventing that third s
from being consumed later. It uses std::basic_streambuf::in_avail
.
std::cin.ignore(std::cin.rdbuf()->in_avail());
如果该方法无效,则可以尝试忽略,直到到达换行符为止。
If that fails to work, you can try to ignore until you reach a line feed.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
这篇关于执行cin后计算标准输入中的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!