Simple Calculator Program

I have been learning C++ for a couple of days and have recently attempted to create a simple calculator program. All seamed to be working fine however I found that after the first calculation, the first digit on any sum would disappear (If it was a two digit number, if not it would not work at all.). Any help or information on why this is happening would be greatly appreciated.

Code...

#include <iostream>

using namespace std;

int main()
{
float x, z;
string y;
int i;

cout << "Please enter a number, a symbol and then another number (seperated by spaces)\ne.g. 3 * 6\n";
while (true)
{
float x=0, z=0;
string y="";

cin >> x >> y >> z;
cin.ignore();

if (y == "*"){
cout << x << "*" << z << "=" << x*z << "\n";
}
else if (y == "/"){
cout << x << "/" << z << "=" << x/z << "\n";
}
else if (y == "+"){
cout << x << "+" << z << "=" << x+z << "\n";
}
else if (y == "-"){
cout << x << "-" << z << "=" << x-z << "\n";
}
cin.ignore();
}
}

Last edited on
closed account (o3hC5Di1)
Hi there,

First off, for reading convenience it's desirable to put [code ] [ /code] tags around your code and use some indentation.

As for your problem, why are you using cin.ignore() here?
If you would use it, it requires some arguments i believe.

Check: http://www.cplusplus.com/reference/iostream/istream/ignore/

Also, as a small matter of style, the mathematical operator is only one character, so you could use datatype char for it.
It saves you from using an extra library (string) and i believe it would take up less memory as well, which on this small scale is of course not as much of an issue.

Hope that helps,

All the best,
NwN
Last edited on
Thanks!
It works after taking care of these things

1)Why multiple declaration of x,y,z?Just use it inside or outside loop.

2)why string y?
Use char y

3)How are you going to end the loop?

4) what is use of i?
Its waste

5)if you enter for example 4 * 5

then pattern
4*5+20
4*5+20
.
.
like this will continue after each enter key pressed,2 times if other key is pressed and "entered"

6)cin.ignore() ignores 1 input in input stream
using it two times.......
Topic archived. No new replies allowed.