Input validation program

Hello everyone I'm making a program that only reads integers between 0-9 but I have a problem with the user being able to input over the max range (9). Check on my bool function from line 47 what I'm doing.

I tried with ((if number.size() > 1) && (number[0] =! '+'))
for stuff like 10, 33, 300, etc but it doesn't work I think the problem is (number[0] =! '+')) but is there another way?


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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>

using namespace std;

int GrabInt ();
bool ValidIntType (string);

int main()
{
    int number;
    
    number = GrabInt();
    
    cout << endl;
    cout << "The integer entered is:  " << number << endl;
    
    cin.ignore();
    cin.get();
    return 0;
    }

int GrabInt()
{
    string number;
    bool ItsValid = false;
    
    while (! ItsValid)
    {
          try
          {
                      cout << "Input a number between 0 - 9" << endl;
                      getline(cin, number);
                      ItsValid = ValidIntType (number);
                      
                      if (! ItsValid)
                      throw number;
                      }
          catch (string e)
          {
                cout << endl;
                cout << "The integer " << e << " is not valid" << endl;
                }
    }
    return atoi(number.c_str());
}

bool ValidIntType (string number)
{
     int i;
     int start = 0;
         
     if (number.size() == 0)  //For empty input
     return 0;                 
     
     if (number[0] == '-')    //For negative numbers
     return 0;          
     
     if (number[0] == '+')    
     {
                   if (number.size() > 2) //For numbers more than +9
                   return 0;              
                                           
                   else
                   {
                       start = 1;                  
                       if (number.size() == 1)  //If the user only input + with no number    
                       return 0; 
                       }                  
                   }
     
     for (i = start; i < number.size(); i++) 
     {                                        
         if (! isdigit(number[i]))            
             return 0;                        
             }
         
         return 1;
     }
                   
      


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Input a number between 0 - 9
+22

The integer +22 is not valid
Input a number between 0 - 9
+333

The integer +333 is not valid
Input a number between 0 - 9
+

The integer + is not valid
Input a number between 0 - 9
-

The integer - is not valid
Input a number between 0 - 9


The integer    is not valid
Input a number between 0 - 9
22

The integer entered is:  22
Hi there,

Very subtle mistake:

1
2
if (number.size() > 2) //For numbers more than +9
                   return 0; 


What you mean to do is:

1
2
if (number.size() >= 2) //For numbers more than +9
                   return 0; 


Or:

1
2
if (number.size() > 1) //For numbers more than +9
                   return 0; 


Hope that helps.

All the best,
NwN

Why not just do something like:

1
2
3
4
5
6
7
if (number < 0 || number > 9)
           {
              cout << "Not a valid number.";
              cin >> number;
            }
...


You could also use isNumber to test whether or not the input is a number.
Last edited on
@NwN

1
2
if (number.size() > 2) //For numbers more than +9
                   return 0; 


I don't think this is a mistake because when I say +9 I'm counting the '+' symbol. So +1 is string size "2" right?

@Moonraker

Could you elaborate more on how to do that exactly?

Thanks for the help you both
When a return type is bool, return true or false.

All of your inputs with "+" are invalid because they are longer than 2 digits, a condition you implemented at line 60.

Your loop at line 71 only checks the first digit, what If I type ""1a12"?

but is there another way?

Two other simple ways.

The first method is to understand that if your program extracts an int, but give the program a string, then you break the cin object. Such a break can be detected and fixed:
1
2
3
4
5
6
7
8
9
10
int i;
cout << "Please enter a number: ";
while (!(cin >> i)) // if the extraction breaks the cin object
{
  cin.clear(); // fix it
  cin.ignore(80, '\n'); // clear the buffer of whatever broke it
  cout << "That wasn't a number. Try again: ";
}
cin.ignore(80, '\n'); // keep the buffer clean
cout << "Your number is:  " << i << endl;


C offers a way to convert a c-string into a number, such math is possible to do yourself.

However, I would imagine that certain c-string functions (length, erase, etc) were written so many times by so many different people that the creators of C++ wanted the entire string class. While c++ strings can be converted to c-strings and then have c methods used on them, the C++ way is to use string streams. A string stream is just like cin/cout, but it is given strings instead, making it very easy to convert a string to any number you want (no need for the many c-string conversion functions).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
  stringstream myStream;
  string word;
  int number;

  cin >> word;
  myStream << word;
  myStream >> number;  // if this fails, number equals zero

  cout << "The word you typed was: " << word << ".  The number is: " << number << endl;

  return 0;
}


Note that leading '+' and '-' are something the >> extractor can handle on it's own.
Last edited on
Just wanted to clarify

All of your inputs with "+" are invalid because they are longer than 2 digits, a condition you implemented at line 60.


Input a number between 0 - 9
+1

The integer entered is:  1


Since it first asks if the input has a '+' at number[0](line 58) then if the string size is more than 2 it will return false.. like +33 or +333

Your loop at line 71 only checks the first digit, what If I type ""1a12"?


Input a number between 0 - 9
1a12

The integer 1a12 is not valid
Input a number between 0 - 9


This checks from number[1] or number[0] (depending if the number as a '+' symbol or not, check line 65) to the number.size()

I'm triying to understand what you said still I'll tell you if I need help with anything thanks for answering =)

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
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
  stringstream myStream;
  string word;
  int number;

  cin >> word;
  myStream << word;
  myStream >> number;  // if this fails, number equals zero

  cout << "The word you typed was: " << word;
  
  if ((number >= 0) || (number < 10))
  
  cout << ".  The number is: " << number << endl;
  
  else
  
  cout << "Only numbers from 0 - 9" << endl;
  
  cin.ignore();
  cin.get();
  return 0;
}


Lol this is so much better than all the mess I was doing but how I could I set a limit? the if doesn't work
Last edited on
Try this:

1
2
3
4
5
6
	cin >> word;
	cin.ignore();
	myStream << word;
	cin >> number;
	cin.ignore();
	myStream >> number;  // if this fails, number equals zero 
The if should look like this. The || (or operator) was true because the number is greater than 0. You need the && (and operator) to make both conditions true to accept a valid input.

 
	if ((number >= 0) && (number < 10))
Last edited on
@Moonraker

True, I was rushing and used || by mistake. Thanks everyone for the help =D
Topic archived. No new replies allowed.