I'm working on a problem where I am trying to validate the user input to verify only digits have been used. I'm trying to use the ASCII code to do so, but I'm stuck. I would greatly appreciate any help that can be provided. Thank you in advance!!!


#include <iostream> 
using namespace std; 
int main() 
    char number[11]; 
    int x = 0; 
    cout << "Please enter the phone number: "; 
    cin >> number; 
    while (number[x] != '\0')
        if ((int(number[x]) > 46 || int(number[x]) < 58)
        cout << int(number[x]); 
        cout << "Invalid characters";
    }//end if
    return 0; 

There are a few options and probably some others that I have forgotten about.

The easiest is to keep the program like you have it (although you have a mismatch in the if/else pair which needs to be fixed) and after you've stepped through the char array with the while loop, compare x to 10, if the 2 are equal it's a valid number. Check the condition of your if statement because it's incorrect, you want numbers that sit in between 46 and 58 rather than anything >46 OR <58.

Another option is to change number to an integer and use the fail bit of the input stream (see second code sample on this site http://www.cs.utk.edu/cs102/lectures/cinLecture.html). If any alpha characters are put in the stream will fail and you can check for that and loop back for more input.

There's also strtol (include <cstdlib>) which can be used on your char array input and the function will return a value if there's a successful conversion. See http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/

This question has already been answered. Start a new discussion instead.