Why does this code work? (question about cin)

When I run the program, and I enter 1-2 (no spaces), I guess the program understands 1-2 is '1','-','2', and not 1-2 or 1 -2 etc.

I was expecting it to produce an error or do something weird. How does cin know where input starts and ends?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main()
{
    cout << "Enter expression: ";

    int lval = 0;
    int rval;
    char op;
    int result;

    cin >> lval >> op >> rval;
    if (op == '+')
        result = lval + rval;
    else if (op == '-')
        result = lval - rval;
    cout << "Result: " << result << endl;

    return 0;

}
How does cin know where input starts and ends?

The extraction operator knows that when inputting values into an int that only "numbers" are allowed. The stream doesn't error out unless the first character is a non-number. It stops processing the variable when it encounters the first non-number. It will then extract one character, any character will do, then proceeds to the next integer value again stopping at the first non-number.

But remember if the user enters 1.0 - 2.0 your program will not function properly because a decimal point is not a valid entry for an int.

You really should have a final else statement in case op is not a '-' or '+' char, and you should probably initialize result to some value when you declare it.

Last edited on
Topic archived. No new replies allowed.