Josh Jacka-Easter
Josh Jacka-Easter

Reputation: 31

How do I validate that the input is numerical?

I have an assignment where the user must enter four inputs, one after another. They are: character, float, float, int.

The main issue is how to check for errors and make sure the used entered valid input?

I have finished the character section but for the floats and ints, how can I check that only numbers are entered and print an error message if letters or symbols are entered?

Thought maybe isdigit() or isaplha() but unsure how to implement their use.

NOTE I have already used scanf() for the input but not sure how to check if input is valid?

Upvotes: 1

Views: 319

Answers (3)

Mike
Mike

Reputation: 49373

I don't know how you're getting your values right now other than you're using scanf() as you mentioned in your post. So lets say you're doing something like this:

char buf[100];     
scanf("%s", buf); 

to get the float/int values. If you want to use isdigit() to verify they are all digit values you can loop as such:

int i = 0;

//need to check for a . for floats
//need to check for a - for negative numbers
while(isdigit(buf[i]) || buf[i] == '.' || buf[i] == '-') 
   i++;
if(i == strlen(buf))   // if we made it to the end of the string
   //we have all digits, do all digit code
else
   //there are numbers or symbols, ask for the number again, or terminate, or whatever

Upvotes: 1

Jens
Jens

Reputation: 72629

If the user is required to enter a string, two floating point numbers and an integer, use

 char s[1024];
 float f1, f2;
 int i;

 if (sscanf (buff, "%s %f %f %d", s, &f1, &f2, &i) == 4) {
    /* Could scan values as expected. */
 } else {
    /* Input not as expected. */
 }

since sscanf returns the number of successfully scanned values. For the details, see the sscanf manual page. Note that scanning an unbounded string with %s has its problems with large inputs. This may not be an issue for homework assignments, but is definitely something to be aware of in production software.

Upvotes: 3

unwind
unwind

Reputation: 399743

With sscanf(), you can try to parse the content of a string as some data type, like an integer (with the %d format specifier) or floating point number (with %g).

The return value of sscanf() tells you if it was successful in interpreting the text as the desired data.

You can also use %n to learn how many characters sscanf() looked at, which is handy when you want to analyze in multiple steps.

Upvotes: 2

Related Questions