C++ 有没有办法检测输入的整数是否为字符串?
我做了一个基本的计算器。一切都按预期工作,唯一的问题是当num1或num2作为字符串/字母输入时,一切都会中断并导致无休止的循环。是否有方法检测整数/双精度是否作为字符串输入?如果有的话,也许我可以把这个计算器做得更好一点C++ 有没有办法检测输入的整数是否为字符串?,c++,C++,我做了一个基本的计算器。一切都按预期工作,唯一的问题是当num1或num2作为字符串/字母输入时,一切都会中断并导致无休止的循环。是否有方法检测整数/双精度是否作为字符串输入?如果有的话,也许我可以把这个计算器做得更好一点 #include <iostream> #include <cmath> using namespace std; int main() { double num1; double num2; string op;
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double num1;
double num2;
string op;
string rep;
bool again1 = true;
bool again = true;
while(again == true)
{
cout << "Enter first number: ";
cin >> num1;
cout << "Operation: ";
cin >> op;
cout << "Enter second number: ";
cin >> num2;
again = false;
again1 = true;
if(op == "+" || op == "add")
{
cout << num1 << "+" << num2 << " = " << num1+num2 << endl;
} else if(op == "-"){
cout << num1 << "-" << num2 << " = " << num1-num2 << endl;
} else if(op == "*" || op == "x"){
cout << num1 << "x" << num2 << " = " << num1*num2 << endl;
} else if(op == "/"){
if(num2 == 0){
cout << "(SYNTAX ERROR)";
} else {
cout << num1 << "/" << num2 << " = " << num1/num2 << endl;
}
}
cout << endl;
while(again1 == true){
again1 = false;
cout << "Would you like to try again? Y/N: ";
cin >> rep;
if(rep == "Y" || rep == "y")
{
again = true;
cout << "Very well!" << endl;
cout << endl;
}
else if(rep == "N" || rep == "n")
{
again = false;
cout << "Ok, see you later!" << endl;
} else {
cout << "Invalid Answer" << endl;
again1 = true;
}
}
}
return 0;
}
#包括
#包括
使用名称空间std;
int main()
{
双num1;
双num2;
字符串op;
字符串代表;
bool again1=真;
布尔再次=真;
while(再次==true)
{
cout>num1;
cout>op;
cout>num2;
再次=假;
again1=真;
如果(op==“+”| | op==“添加”)
{
cout您可以在字符串中获取输入,然后您可以根据需要使用任何适当的方法将这些字符串转换为整数或其他数据类型
如果无法进行转换,它可能会抛出一个无效的\u参数
异常,您可以捕获该异常并要求用户输入有效的数字