Tuesday, October 19, 2010

C - One way to get input from keyboard

references:
1. Oualline, S. (1997). Practical C Programming, 3rd ed., O'Reilly Media, Inc.
2. BJ Furman | ME 30 Computer Applications | A Better Way to Get Input From the Keyboard.doc

/* Example of a robust way to get input from the keyboard*/
#include <stdio.h>
/*declare variables that you want to read in*/
char char1;
int var1;
float var2;
char string1[20]; /*an array to hold 19 characters*/

char line[100]; /*for the line of user input*/
/*put a user prompt here*/
/*get and process the user input*/

fgets(line, sizeof(line). stdin);
sscanf( line, "%s %c %f %d", string1, &char1, &var2, &var1);


Step-by-Step:
1. Declare variables you want to use to store the input
2. Declare an array of characters that is long enough to contain what the user will enter
         char line[100];
3. Get the line of input and process it to store the variables
         fgets (line, sizeof(line), stdin);
        sscanf (line, "%s %c %f %d", string1, &char1, &var2, &var1);

How Things Work:
1. fgets() gets a line of input (note: 100 characters maximum including the EOL) from stdin (the keyboard)
2. sscanf() (string scanf()) scans the input line string and processes it according to the control string (i.e., the conversion specifications between the double-quotes)
3. sscanf() must have pointers to the variables (hence ampersands in front of the variable names, and the use of a character array (string[20]) in the parameter list )
4. * Of course the conversion specifications in the control string must match the list of variables in order for this to work properly.