Input Validation

I'm supposed to reproduce the function isValidInt to validate the format for
an integer which has been entered using the keyboard.

Test your function using the following test cases:

-1234
5674.25
$1700
Here's my code:

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
  #include <iostream>
#include <string>
#include <sstream>

using namespace std;

string value;
int number;

int main()
{
cout << "Enter an integer: ";
  getline(cin, value);

bool isvalidInt( string str )
{
     int start = 0;          //start position in the string
     int i;                    //   position in the string         
     bool valid = true;    //assume a valid integer 
     bool sign = false;    //assume no sign 

    //check for an empty string
	if (str.length() == 0)    valid = false;

//Check the first character
if( valid )           
       // check for a leading sign
        if ( str.at(0) == '-'|| str.at(0) == '+' ) 
        { 
	         sign = true;
	         start = 1;              // start checking for digits after the sign
            //check that there is at least one character after the sign
            if ( sign && str.length() == 1 )
                  valid = false;
        }
        else if(  ! isdigit( str.at(0) )   )        // is it a non-digit character 
               valid = false;
               
               
//now we can check the string for all digits, 
//which we know has at least one non-sign char
     i = start;

     //we have checked  i  number of chars so far
     while( valid  &&  i != str.length() )
     {
         if(  ! isdigit(str.at(i))  ) 
                valid = false;          //found a non-digit character

	    i++;                               // move to next character
     }

    if ( ! isValidInt(value) )
       cout << "The value you entered is not a valid integer.\n\n";
  else
  {
      number = atoi(value.c_str());
  }   
   return valid;


Can someone please explain what I'm doing wrong?
Last edited on
function definitions must be outside of functions (including main function)

by the way where does isvalidInt end?
if like I'm guessing at line 59 you should put a closing } after it
and outside of the function it isn't called so all your hard-work won't get executed at all
Last edited on
Can you explain what you mean by "
and outside of the function it isn't called so all your hard-work won't get executed at all
"?
Topic archived. No new replies allowed.