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!!!

*Delilah*

#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]); 
        x++; 
    } 
 else
    {
        cout << "Invalid characters";
    }//end if
 
    system("pause");
    return 0; 
}

Recommended Answers

All 2 Replies

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/

I think '0' is 48 (x30) in ASCII code? so the condition should be >47 && <58 instead?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.