zoukankan      html  css  js  c++  java
  • 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 } 

      运行结果

      

  • 相关阅读:
    数学中求余数问题
    点击事件后根据url保持相应导航高亮
    TP5和TP3.2的使用区别
    在已部署好的docker环境下配置nginx项目路径
    Tp5整理
    cookies、sessionStorage和localStorage的异同点
    CSS的长度单位
    Linux sed识别HTML标签
    css样式读取
    seller vue配置路径相对路径【组件 只写简单路径】
  • 原文地址:https://www.cnblogs.com/MakeView660/p/6077371.html
Copyright © 2011-2022 走看看