English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

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.

2006-08-07 21:01:04 · 2 answers · asked by Anonymous in Computers & Internet Programming & Design

2 answers

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", &n);
----------------
--- new code ---
char user_input[1024];
int n;
printf("Enter a number: ");
scanf("%s", user_input);
sscanf(user_input, "%d", &n);
-------------------
This will enable you to prevent crashes, as well as print suitable error messages based on user input.

2006-08-07 23:45:04 · answer #1 · answered by swami060 3 · 1 0

Here is a programme that prints only numeric datatypes on the screen.

# include //Standard libraty
# include //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.

}
}

}

2006-08-07 21:24:48 · answer #2 · answered by Bachelor boy 2 · 0 0

fedest.com, questions and answers