user7091569 user7091569 - 1 month ago 11
C++ Question

c++ istream operator >> expecting arbitrary input type

I have a task where I expect random input of

chars
or
ints
. Is there any way I can understand what is coming next and say
cin >> int
, or
cin >> char
. I want to do it with the
istream operator >>
, because they told us not to do it with a parser. To be precise, I expect an input of a prefix expression. So I don't know when to read an operator, when to read a number. If you have any suggestions I'd appreciate them :)

Answer

You can do, without a parser:

int n;
cin >> n;

if (cin.good())
{
    // manage integer
}   
else
{
    char c;
    cin.clear();
    cin >> c;

    // manage character
}
Comments