-
Notifications
You must be signed in to change notification settings - Fork 0
/
getInteger.cpp
57 lines (49 loc) · 1.82 KB
/
getInteger.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/***************************************************************************************************
* This function retrieves an integer from the user, validates that the user entered an integer
* and passes the integer back to the calling function.
* ************************************************************************************************/
int getInteger()
{
std::cout << "Please enter the integer that corresponds to your menu choice " << std::endl;
std::cout << "by typing the integer and pressing the enter key. " << std::endl;
int choice = 0;
std::string input = "";
while(true)
{
getline(std::cin, input);
std::stringstream myStream(input);
if(isInteger(input) && myStream >> choice)
break;
std::cout << "You must enter an integer" << std::endl;
}
return choice;
}
int getInteger(int min, int max)
{
std::cout << "Please enter an integer " << min << " through " << max << std::endl;
std::cout << "by typing the integer and pressing the enter key. " << std::endl;
int choice = 0;
std::string input = "";
while(true)
{
getline(std::cin, input);
std::stringstream myStream(input);
if(isInteger(input) && myStream >> choice)
{
if(choice >= min && choice <= max)
break;
}
std::cout << "You must enter an integer" << std::endl;
}
return choice;
}
/****************************************************************************************************
* This integer checks that a string passed to it is a positive integer
* *************************************************************************************************/
bool isInteger(const std::string& s)
{
std::string::const_iterator itr = s.begin();
while(itr != s.end() && isdigit(*itr))
++itr;
return !s.empty() && itr == s.end();
}