在實際的工做中,須要提取程序中的字符串信息,可是程序中常常將一些數字當作字符串來進行處理,例如錶盤的刻度信息,這時候就須要判斷字符串是否全爲數字,來進行真正意義上的字符串提取。下面介紹了判斷字符串是否全爲數字的方法,僅供參考。ios
方法一:判斷字符的ASCII範圍(數字的範圍爲48~57)spa
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對象 code
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 }
運行結果:對象