how can I validate user input for only entering numbers, if user entered something (string, character, etc) instead of number, it should show the error in. c programming language
Asked
Active
Viewed 86 times
-1
-
4@Blaze In general it is not recommended to use `scanf`. Too many things can go wrong. For example if this code is run in loop. – Eugene Sh. Oct 23 '19 at 14:53
-
2[`strtod()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtod.html) ... `char *err; double value = strtod(input, &err); /* check errno, *err */` or use [`strtoull()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtoul.html) – pmg Oct 23 '19 at 14:54
-
1Don't use `scanf`. Use `fgets` and scan the string yourself using possibly `sscanf` or `strtod`, `strtol` etc. – Jabberwocky Oct 23 '19 at 14:59
-
1scanf may result in false positives, eg with `if (sscanf("42foo", "%d", &n) == 1) /* "42foo" accepted as number */;` – pmg Oct 23 '19 at 15:00
-
1Actually the `scanf` family of functions should only be used if you're sure the input format _actually_ matches the scanf format string. You can't be sure of anything with user input. – Jabberwocky Oct 23 '19 at 15:08
-
Write a dedicated function, passing a prompt message, and the min/max acceptable values. – Weather Vane Oct 23 '19 at 15:09
-
The second answer is usually my approach. Not familiar with the C99 functions in the first answer, but they certainly look useful: https://stackoverflow.com/questions/7021725/how-to-convert-a-string-to-integer-in-c?rq=1 – yano Oct 23 '19 at 15:15
1 Answers
-1
This program will find and gives error when it doesn't find any number in the input and it will specify the index in which the character is given as a input.
if you wanna declare the numbers you can by using a series of if-else conditions.
here I am basically differentiate the numbers and the character.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i;
char a[100];
printf("enter the input value");
replay:
scanf("%s",&a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]=='1'||a[i]=='2'||a[i]=='3'||a[i]=='4'||a[i]=='5'||a[i]=='6'||a[i]=='7'||a[i]=='8'||a[i]=='9'||a[i]=='0')
{
printf("It Contains only numbers");
}
else
{
printf("\n error occured in %c position %d:\nEnter a valid number:",a[i],i);
goto replay;
}
}
}

raj123
- 564
- 2
- 10
- 27
-
the if statement in 13th line of the code should be considered to be included the code – BalaSriRamanan Oct 23 '19 at 18:06