user2084986
user2084986

Reputation:

cin doesn't function properly while reading math operations

I tried to write a function that chop an expression into tokens as below.

while(true)
{
    cin >> d_tmp;               
    if(!cin){
        cin.clear();
        cin >> ch_tmp;

        cout << ch_tmp << endl;
    }
    else
    {
        cout << d_tmp << endl;
    }
}

However, the function didn't work as I expected. It worked fine when I entered a sequence of random number and character When I typed in "a 3 b" returns 'a' '3' and 'b', but when I typed "3 + 4", all that return are '3' and '4'.

I've tried several testcases with the following code. It seems that if I want the program to print '3' '+' '4', I have to type in "3 ++ 4". This totally confuses me. Anyone have any idea on this??? Thanks!

Upvotes: 3

Views: 127

Answers (2)

spiritwolfform
spiritwolfform

Reputation: 2293

The "+" character is eaten by cin >> d_tmp; when it tries to parse it as int and sets the fail flag

Upvotes: 1

jxh
jxh

Reputation: 70442

You state that the types of the variables are:

int d_tmp;
char ch_tmp;

With the input 3 + 4, the execution goes as follows:

  • cin >> d_tmp; reads 3, reads space, stops
  • if(!cin) is false, goes to else, and prints 3
  • cin >> d_tmp; reads +, reads space, errors
  • if(!cin) is true
  • cin >> ch_tmp; reads 4

The number parser of the input stream treats +12 as a number, so it will consume a + if it sees it.

Upvotes: 1

Related Questions