Why does my calculator code work when I run it improperly?

Write your question here.
I was trying to make a calculator program, and while this code works when I run it the way it's supposed to be run ie: I input a number, press enter input another etc, it also works if I just type in my whole equation on the first prompt and press enter. If anyone could explain why this works, I'd appreciate it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  #include <iostream>

using namespace std;


int main ( )

{
int x;
cin >> x;

char operation;
cin>> operation;

int y;
cin >> y; 


switch (operation)
{
case '+':

cout << x + y;

break;

case '*':
cout << x *y;

break;

case '/':
cout << x / y;
break;

case '-':
cout << x - y;
break;
}
Input streams work like a large buffer that stores everything entered into it. 'cin' however, only takes out of that buffer the amount of info (ignoring whitespace) as the data you tell it.

so when you enter "2 + 4" all at once at the prompt, all of that is stored in the input stream. Then cin >> x; will pull the first integer '2' from the stream. the next 'cin >> operation;' looks at the stream, sees that there is already info there (the '+') and grabs it from the stream rather than waiting for you to type more. then 'cin >> y;' does the same, grabbing the '4'.
It's actually really interesting! The stream does not wait for you to enter an int, press enter, enter a char, press enter, and then enter another int. Whatever you type in, it remains in the stream (or buffer, I don't know the correct terminology in this case) until the next call to read in some data. This is why this bit of code:
1
2
3
int x, y;
char operation;
cin >> x >> operation >> y;

does the exact equivalent of what your code does.

Think about how you use cout because it is equivalently the same. You don't have to make a call to cout every time you want to output a literal or variable to the screen, but you can just repeatedly use the insertion operator in one statement to output data.
Thanks for your help guys. Any suggestions on how I could make the program run so that it will output an error message if the input isn't as required?
Topic archived. No new replies allowed.