检测输入值是否为整型

 1 #include <iostream>
 2 #include <climits>
 3 #include <string>
 4 #include <math.h>
 5 #define _CRT_SECURE_NO_WARNINGS
 6 
 7 bool is_num(char*); //Check whether the input only consists of number or not
 8 bool test_limits(double); //Check whether the input falls within the C++ integer limits
 9 
10 int main()
11 {
12     using namespace std;
13 
14     //Get the initial input
15     cout << "Yo, dude! Enter an integer value:\n";
16     char str[999];
17     cin >> str;
18 
19     //Set an indicator
20     bool pass = false;
21 
22     //Create a pointer points to the addresss of the first character of the input
23     char *num;
24 
25     //Create a double variation for the bound test
26     double numberForTest = 0;
27 
28     //Valuation
29     while (!pass)
30     {
31         num = str;
32 
33         //Check Round 1
34         if (!is_num(num))
35         {
36             cout << "Please enter an integer\n";
37             cin >> str;
38         }
39 
40         //Check round 2
41         else
42         {
43             //Get the double form of the input 
44             for (int temp = strlen(str) - 1; *num; num++, temp--)
45             {
46                 numberForTest += (int(*num) - 48)*pow(10, temp);
47             }
48 
49             if (!test_limits(numberForTest))
50             {
51                 cout << "Out of range -- please try again:\n";
52                 numberForTest = 0;
53                 cin >> str;
54             }
55             else
56                 pass = true;
57         }
58     }
59 
60     cout << "You have entered the integer " << numberForTest << "\nBye\b";
61     return 0;
62 }
63 
64 bool is_num(char *x)
65 {
66     for (; *x; x++)
67     {
68         if ('0' <= *x&&*x <= '9')
69             continue;
70         else
71             return false;
72     }
73     return true;
74 }
75 
76 bool test_limits(double a)
77 {
78     if (INT_MIN <= a && a <= INT_MAX)
79         return true;
80     else
81         return false;
82 }

 

posted @ 2020-09-02 00:25  Maxproto  阅读(167)  评论(0)    收藏  举报