Possible Duplicate:
How to determine if a string is a number with C++?
I have written a very simple calculator program in C++. Here it is:
#include <iostream>
#include <string>
using namespace std;
int main()
{
double num1;
double num2;
string op;
double num3;
int x;
bool y = false;
do
{
cout<<"Press t to terminate the application"<<endl;
cout<<"Enter the first number"<<endl;
cin>>num1;
cout<<"Enter the operator"<<endl;
cin>>op;
cout<<"Enter the next number"<<endl;
cin>>num2;
if(op=="/"&&num2==0)
{
cout<<"You are attempting to divide by 0. This is impossible and causes the destruction of the universe. However, the answer is infinity"<<endl;
y = true;
}
if(y==false)
{
if(op=="+") {
num3 = num1+num2;
}
else if(op=="-") {
num3 = num1-num2;
}
else if(op=="*"||op=="x"||op=="X") {
num3 = num1*num2;
}
else {
num3 = num1/num2;
}
cout<<endl;
cout<<endl;
cout<<"Answer:"<<num3<<endl<<endl;
}
} while(x!=12);
return 0;
}
As you can see, I want to allow people to terminate the application by pressing 't'. This obviously won't work because cin
will try and assign a letter to a double
(if I do press 't' the application crashes). I am planning to use strings instead to get the input, but how would I test if the string is a letter or a number?