在實際的工作中,需要提取程式中的字元串資訊,但是程式中經常将一些數字當做字元串來進行處理,例如表盤的刻度資訊,這時候就需要判斷字元串是否全為數字,來進行真正意義上的字元串提取。下面介紹了判斷字元串是否全為數字的方法,僅供參考。
方法一:判斷字元的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 }
運作結果: