C++判断字符串是否为数字

来源:互联网 发布:剑灵火炮兰数据 编辑:程序博客网 时间:2024/06/05 20:26


思路1:挨个字符判断其ASCII码是否属于数字范围 48--57

转为ASC码 :int i=(int)a; //a是字符
string s;
int tmp = (int)s[i];


思路二

C++实例:

#include <iostream>#include <sstream>using namespace std;bool isNum(string str);int main( ){string ss1="2y5r";string ss2="2558";if(isNum(ss1)){cout<<"ss1 is a num"<<endl;}else{cout<<"ss1 is not a num"<<endl;}if(isNum(ss2)){cout<<"ss2 is a num"<<endl;}else{cout<<"ss2 is not a num"<<endl;}return 0;}bool isNum(string str){    stringstream sin(str);    double d;    char c;    if(!(sin >> d))        return false;    if (sin >> c)        return false;    return true;}

输出结果:

ss1 is not a num

ss2 is a num

0 0
原创粉丝点击