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

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

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

  

复制代码
 1 #include <iostream>
 2 using namespace std;  
 3 
 4 bool AllisNum(string str); 
 5  
 6 int main( void )  
 7 {  
 8 
 9     string str1 = "wolaiqiao23";  
10     string str2 = "1990";  
11 
12     if (AllisNum(str1))
13     {
14         cout<<"str1 is a num"<<endl;  
15     }
16     else
17     {
18         cout<<"str1 is not a num"<<endl;  
19     }
20 
21     if (AllisNum(str2))
22     {
23         cout<<"str2 is a num"<<endl;  
24     }
25     else
26     {
27         cout<<"str2 is not a num"<<endl;  
28     }
29 
30     cin.get();
31     return 0;  
32 }  
33  
34 bool AllisNum(string str)  
35 {  
36     for (int i = 0; i < str.size(); i++)
37     {
38         int tmp = (int)str[i];
39         if (tmp >= 48 && tmp <= 57)
40         {
41             continue;
42         }
43         else
44         {
45             return false;
46         }
47     } 
48     return true;
49 }  
复制代码

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

复制代码
 1 #include <iostream>
 2 #include <sstream>  
 3 using namespace std;  
 4 
 5 bool isNum(string str);  
 6 
 7 int main( void )  
 8 {
 9     string str1 = "wolaiqiao23r";  
10     string str2 = "1990";  
11     if(isNum(str1))  
12     {  
13         cout << "str1 is a num" << endl;  
14     }  
15     else
16     {  
17         cout << "str1 is not a num" << endl;  
18 
19     }  
20     if(isNum(str2))  
21     {  
22         cout<<"str2 is a num"<<endl;  
23     }  
24     else
25     {  
26         cout<<"str2 is not a num"<<endl;  
27 
28     }  
29 
30     cin.get();
31     return 0;  
32 }  
33 
34 bool isNum(string str)  
35 {  
36     stringstream sin(str);  
37     double d;  
38     char c;  
39     if(!(sin >> d))  
40     {
41         return false;
42     }
43     if (sin >> c) 
44     {
45         return false;
46     }  
47     return true;  
48 } 
复制代码

  运行结果

  

 

posted on   我来乔23  阅读(56668)  评论(1编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示