Using the C Programming Language, does anyone know how to validate the users input so they can only enter either int, float or double data types (no char!). Usually if you enter a char when your supposed to enter a digit, the program bombs itself. I need to stop the operator from inputing strings or characters.
Validating user input in C programming language. How to stop users entering characters instead of digits!?
Hi,
A standard practice to handle this scenario is to accept only text input from the user, and then use a function like sscanf to convert it to the required format.
For example:
--- old code--
int n;
printf("Enter a number: ");
scanf("%d", %26amp;n);
----------------
--- new code ---
char user_input[1024];
int n;
printf("Enter a number: ");
scanf("%s", user_input);
sscanf(user_input, "%d", %26amp;n);
-------------------
This will enable you to prevent crashes, as well as print suitable error messages based on user input.
Reply:Here is a programme that prints only numeric datatypes on the screen.
# include %26lt;stdio.h%26gt; //Standard libraty
# include %26lt;ctype.h%26gt; //Header file that will check datatype
main ()
{
char c;
while (getch()!='.')//Exit when . is pressed.
{
c=getch();//Get the character from the keyboard
if (isdigit(c))//Validate data type
{
printf("%c",c);//Print datatype only if it is numeric.
}
}
}
paid survey
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment