c++中怎么判断一个string类型的字符串变量是否为数字?

注意,不是单个字符,而是字符串?
2024-11-16 23:22:13
推荐回答(5个)
回答1:

你可以分别判断字符串中每个字符是否是数字,如果是则int i设为0,否则就设为1,只要有不是0的就判断为不是数字,否则就是数字

回答2:

可以先判断一下这个字符串中的每个字符的ascii是否都为数字和小数点及小数点只有一个,如果为则类型转换为数字

回答3:

#include
#include
#include
using namespace std;

bool isnum(string s)
{
stringstream sin(s);
double t;
char p;
if(!(sin >> t))
return false;
if(sin >> p)
return false;
else
return true;
}

int main()
{
string s;
while(cin >> s)
{
if(isnum(s))
cout << s << " is a number." << endl;
else
cout << s << " is not a number." << endl;
}
}

回答4:

string s;
cin>>s;
判断(int)s[x]是否在48-57(ASCII码)之内

回答5:

。。。。只是换经验值