Counting the number of characters in standard input after a cin has been executed

我的梦境 提交于 2020-01-07 08:35:30

问题


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
}

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.

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.


回答1:


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');



回答2:


It is quite unclear what you mean but one meaning could be that you want to ignore all characters on the current line. You don't need to know the number of characters to do so:

std::cin.ignore(std::numeric_limits<std::size_type>::max(), '\n');

The above statement will ignore all the characters until it has extracted a newline character.




回答3:


Doing some Googling I have found this article on how to cope with extraneous characters in cin.

Apparently it is not a good practice to use >> on std::cin directly. Use it like this,

int a;
std::string line;
std::getline( cin, line );
std::stringstream ss( line );

if ( ss >> a )
    // Success

// Failure: input does not contain a valid number

Since we are reading till \n each time using std::getline(), extraneous characters are also extracted from std::cin and put into line.

Code source



来源:https://stackoverflow.com/questions/12242078/counting-the-number-of-characters-in-standard-input-after-a-cin-has-been-execute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!