可能重复:
如何使用 C++ 确定字符串是否为数字?
我用 C++ 编写了一个非常简单的计算器程序。这里是:
#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;
}
如您所见,我想让人们通过按“t”来终止应用程序。这显然行不通,因为cin
会尝试为 a 分配一个字母double
(如果我按“t”,应用程序将崩溃)。我打算使用字符串来获取输入,但是我将如何测试字符串是字母还是数字?