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

在实际的工作中,需要提取程序中的字符串信息,但是程序中经常将一些数字当做字符串来进行处理,例如表盘的刻度信息,这时候就需要判断字符串是否全为数字,来进行真正意义上的字符串提取。下面介绍了判断字符串是否全为数字的方法,仅供参考。

  方法一:判断字符的ASCII范围(数字的范围为48~57)
C++ 判断字符串是否全是数字


#include <iostream>
using namespace std;  

bool AllisNum(string str); 
 
int main( void )  
{  

    string str1 = "wolaiqiao23";  
    string str2 = "1990";  

    if (AllisNum(str1))
    {
        cout<<"str1 is a num"<<endl;  
    }
    else
    {
        cout<<"str1 is not a num"<<endl;  
    }

    if (AllisNum(str2))
    {
        cout<<"str2 is a num"<<endl;  
    }
    else
    {
        cout<<"str2 is not a num"<<endl;  
    }

    cin.get();
    return 0;  
}  
 
bool AllisNum(string str)  
{  
    for (int i = 0; i < str.size(); i++)
    {
        int tmp = (int)str[i];
        if (tmp >= 48 && tmp <= 57)
        {
            continue;
        }
        else
        {
            return false;
        }
    } 
    return true;
}  

  方法二:使用C++提供的stringstream对象 


#include <iostream>
#include <sstream>  
using namespace std;  

bool isNum(string str);  

int main( void )  
{
    string str1 = "wolaiqiao23r";  
    string str2 = "1990";  
    if(isNum(str1))  
    {  
        cout << "str1 is a num" << endl;  
    }  
    else
    {  
        cout << "str1 is not a num" << endl;  

    }  
    if(isNum(str2))  
    {  
        cout<<"str2 is a num"<<endl;  
    }  
    else
    {  
        cout<<"str2 is not a num"<<endl;  

    }  

    cin.get();
    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;  
} 

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

1. 全库网所有资源均来源于用户上传和网络,如有侵权请发送邮箱联系站长处理!
2. 如果你有好的资源或者原创教程,可以到审核区投稿发布,分享会有钻石奖励和额外收入!
3. 全库网所有的源码、教程等其它资源均源于用户上传发布,如有疑问,可直接联系发布作者处理
4. 如有链接无法下载、失效或广告,请联系全库网管理员核实处理!
5. 通过发布原创教学视频或优质源码资源可以免费获得全库网站内SVIP会员噢
6.全库网管理猿邮箱地址:admin@qkuser.com,我们会在收到您的邮件后三个工作日内完成处理!
7. 如遇到加密压缩包,默认解压密码为"qkuser.com",如遇到无法解压的请联系管理员!

全库网 » C++ 判断字符串是否全是数字