C++如何判断一个string字符串,是否是数字

方法一:判断字符的ASCII范围(数字的范围为48~57)


#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))  
	{
		/*解释: 
            sin>>t表示把sin转换成double的变量(其实对于int和float型的都会接收),
			如果转换成功,则值为非0,如果转换不成功就返回为0 
        */
		return false;
	}
	if (sin >> c) 
	{
		/*解释:
		此部分用于检测错误输入中,数字加字符串的输入形式(例如:34.f),在上面的的部分(sin>>t)
		已经接收并转换了输入的数字部分,在stringstream中相应也会把那一部分给清除,
		此时接收的是.f这部分,所以条件成立,返回false 
          */ 
		return false;
	}  
	return true;  
}



  • 11
    点赞
  • 67
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值