C++如何判断收到消息是字符串还是数字

2025-03-15 19:08:54
推荐回答(5个)
回答1:

只需要 挨个字符判断其ASCII码是否属于数字范围 48--57

转为ASC码 :int i=(int)a; //a是字符

string s;

int tmp = (int)s[i];

C++实例

#include   
#include   
using namespace std;  
  
bool isNum(string str);  
int main( )  
{  
  
    string ss1="2y5r";  
    string ss2="2558";  
    if(isNum(ss1))  
    {  
        cout<<"ss1 is a num"<    }  
    else{  
        cout<<"ss1 is not a num"<  
    }  
    if(isNum(ss2))  
    {  
        cout<<"ss2 is a num"<    }  
    else{  
        cout<<"ss2 is not a num"<          
    }  
    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

回答2:

很好办嘛,那你就检查消息中是否含有字母就行了,有字母的就是字符串,没有的就是数字了!
将字符串赋值给数组a[100],然后用循环对比ascii码,比如:
asc(a[i]) asc(a[i])>asc('9')则也包含非数字字符,也为字符串。
只要判断出有一个为非数字字符即为字符串。

回答3:

#include
using namespace std;

bool IsNumber(char *str)
{
int nLen = strlen(str);
// 判断小数的话只需要增加小数点的处理就好了
int nCount = 0;// 记录小数点的个数

for (int i=0; i {
if (str[i] < '0' || str[i] > '9')
{
return false;
}

// 判断小数点
if (str[i] == '.')
{
if (nCount == 0)
{
nCount++;
}
else
{
return false;
}
}

}

return true;
}

int main()
{
char str[100];
do
{
cin.getline(str, sizeof(str));
} while (!IsNumber(str));
}

自己写个这样的函数

回答4:

判断字符的ASCII值

回答5:

#include
#include
using namespace std;
bool isnum(string value)
{
return value.end() == std::find_if_not(value.begin(), value.end(),
[](int c) {return isdigit(c); });
}