So I've been reading through Programming Principles & Practice Using C++ and I got the the part where he takes you through the process of making a simple calculator, only I've written out the code exactly as he's written it and it doesn't work. I've had a similar problem with a program I've tried to write myself before as well. Here's the code thus far, bearing in mind he will be leaving stuff out and pointing out why some things need to be adjusted through this chapter. I just want to know why I'm getting the problems I'm getting:
#include "../../std_lib_facilities.h"
int main()
{
cout << "Plase enter expression (we can handle +, -, * and /): ";
int lval = 0;
int rval;
char op;
cin >> lval;
if(!cin) error("No first operand.");
while(cin >> op){
cin >> rval;
if(!cin) error("No second operand.");
switch(op){
case'+':
lval +=rval;
break;
case'-':
lval -=rval;
break;
case'*':
lval *=rval;
case'/':
lval /=rval;
break;
default:
cout << "Result: " << lval << '/n';
keep_window_open();
return 0;
}
}
error("Bad expression.");
}
That's the code. What happens is, for example: If I type in say "5+7" and press enter, nothing happens and it just goes to the next line. If I type "5+7" again on the next line and press enter again I get "Result: 1212142".
Why doesn't it work the first time I press enter? Is there a problem in the order of the code? Is it a problem completely separate from the code?
I've had the problem with a program not doing anything when you enter something till the second time, where it seems to combine the two or whatever and does something very strange before.
#include <iostream>
#include <cstdlib>
usingnamespace std;
void error(const std::string& input)
{
cerr << "ERROR: " << input << endl;
exit(2); //Exit codes are funnnnnn
}
int main()
{
cout << "Plase enter expression (we can handle +, -, * and /): ";
int lval = 0;
int rval;
char op;
cin >> lval;
if(!cin) error("No first operand.");
while(cin >> op){
cin >> rval;
if(!cin) error("No second operand.");
switch(op){
case'+':
lval +=rval;
break;
case'-':
lval -=rval;
break;
case'*':
lval *=rval;
case'/':
lval /=rval;
break;
default:
break;
}
cout << "Result: " << lval << std::endl;
/*We may still have data in the stream. Need to flush it */
std::cin.ignore(256, '\n'); //256 is a random number. It's possible this won't work if theres more than 256 bytes in the stream.
std::cin.ignore(); //After we flush, interrupt.
return 0;
}
error("Bad expression.");
}
Okay even though I have no idea what you've done as we haven't covered exit codes or 'flushing' yet in the book, it seems to have almost worked. It's just multiplying integers that doesn't work now.
st_lib_facilities.h is the library that the book asks you to use for the majority of it.
Right, I think I'm just going to read through this chapter now rather than writing out the calculator as it goes along. Thank you anyway.