Well I think the below program is okay but it is giving following error
op: undeclared identifier
I just cant understand why this is happening because it is the same exact code I copied it from "programming principles and practice using c++".
#include "../../std_lib_facilities.h"
using namespace std;
int main()
{
cout << "Please enter an expression. We can handle +,-,* and /" << "\n";
cout << "Add an x to end expression" << "\n";
int lval = 0;
int rval;
cin >> lval;
if (!cin) error("No first operand");
for (char op; cin >> op;)
if (op != 'x') cin >> rval;
if (!cin) error("No second operand");
switch (op) {
case'+':
lval += rval;
break;
case'-':
lval -= rval;
break;
case'*':
lval *= rval;
break;
case'/':
lval /= rval;
break;
default:
cout << "Result: " << lval << '\n';
keep_window_open();
return 0;
}
}
The scope of variables declared in for loops is limited to the for loop. In order to use op outside the for loop you need to change it to
char op;
for (; cin >> op;)
But while we are changing things lets just make this a while loop
char op;
while (cin >> op)
Some compilers allowed using variables declared in a for loop outside the for loop but that is not standard and it should not be relied on. An easy way to tell if you have a non conforming compiler is to run
int main()
{
for(int i = 0; i < 0; i++) {}
i++;
}
The i++ should cause an error(example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With