C++之判斷字符串是否是數字


文章轉載自https://blog.csdn.net/Richard__Ting/article/details/80772174

判斷是否為數字
 1 #include <iostream>
 2 #include <iomanip>
 3 #include <string>
 4 #include <cctype> //判斷字符類型需要的頭文件
 5 using namespace std;
 6 int main()
 7 {   string str;
 8     int len;
 9     int n;
10     int count;
11     cin>>n;
12     for(int i = 0;i < n;i++){
13         cin>>str;
14         count = 0;
15         len = str.length();
16         for(int j = 0;j < len;j++){
17             if(isdigit(str[j])){ //判斷字符是否是數字
18                 count++;//計數
19             }
20         }
21         cout<<count<<endl;
22     }
23     return 0;
24 }
其他

cctype中還有其他函數,如:

isalnum() 用來判斷一個字符是否為英文字母或數字,相當於 isalpha(c) || isdigit(c)

isalpha() 用來判斷一個字符是否是英文字母,相當於 isupper(c)||islower(c)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM