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

本文介绍了两种在C++中检查字符串是否仅包含数字的方法。第一种方法通过遍历字符串并检查每个字符的ASCII值来确定;第二种方法利用C++标准库中的stringstream对象进行尝试性解析。
部署运行你感兴趣的模型镜像

方法一:判断字符的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;  
}



您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值