Booleans (!cin and op!)?

Greetings!
I had trouble understanding what exactly (!cin) and (op!='x') signify in this code. From my understanding, it is some sort of boolean, but in the context of this code, I don't quite understand what it is doing, and what the condition is for providing no operand.

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
 cout << "Please enter expression (we can handle +, –, *, and /)\n";
cout << "add an x to end expression (e.g., 1+2*3x): ";
int lval = 0;
int rval;
cin>>lval; // read leftmost operand
if (!cin) error("no first operand");
for (char op; cin>>op; ) { // read operator and right-hand operand
// repeatedly
if (op!='x') cin>>rval;
if (!cin) error("no second operand");
switch(op) {
case '+':
lval += rval; // add: lval = lval + rval
break;
case '–':
lval –= rval; // subtract: lval = lval – rval
break;
case '*':
lval *= rval; // multiply: lval = lval * rval
break;
case '/':
lval /= rval; // divide: lval = lval / rval
break;
default: // not another operator: print result
cout << "Result: " << lval << '\n';
keep_window_open();
return 0;
}
}
error("bad expression");
}
Hi,

!cin is the condition if the console input doesn't matches the type of variable assigned by the code

for eg in your case lval is a integer, if someone inputs, lets say a character the if statement will be executed

and the op!='x' simply means if the variable op is not x

Hope it helps
if (!cin)
If statements take a bool value. If something other than a bool is passed it must be converted to bool. When a stream such as std::cin is converted to a bool. The result is false if the stream is in a fail state or true if the stream is not in a fail state.

A stream will be placed in a fail state when input fails. One reason input might fail is when you try to input a char into an integer.
Thank you both for the explanations. It makes sense now!
welcome :)
Topic archived. No new replies allowed.