Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help
next up previous contents
Next: Source File organisation Up: Interactive Previous: Output   Contents

Input

scanf is a useful-looking routine for getting input. It looks for input of the format described in its 1st argument and puts the input into the variables pointed to by the succeeding arguments. It returns the number of arguments successfully read.

Suppose you wanted the user to type their surname then their age in. You could do this:-

int age;
char name[50];
int return_val;
main(){
  printf("Type in your surname and age, then hit the Return key\n");
  while(TRUE){
    return_val= scanf("%s %d", name, &age);
    if (return_val == 2)
       break;
    else
       printf("Sorry. Try Again\n");  
  }
}

If you use scanf in this way to directly get user input, and the user types in something different to what scanf() is expecting, scanf keeps reading until its entire input list is fulfilled or EOF is reached. It treats a newline as white space. Thus users can become very frustrated in this example if, say, they keep typing their name, then hitting Return. A better scheme is to store user input in an intermediate string and use sscanf(), which is like scanf() except that its first argument is the string which is to be scanned. E.g. in

...
int ret, x, y, z;
ret = sscanf(str,"x=%d y=%d z=%d", &x, &y, &z);
...
sscanf, given a string `x=3 y=7 z=89', will set the x, y, and z values accordingly and ret will be set to 3 showing that 3 values have been scanned. If str is `x+1 y=4', sscanf will return 2 and won't hang and you can print a useful message to the user.

To read the original string in, fgets() is a safer routine to use than gets() since with gets() one can't check to see if the input line is too large for the buffer. This still leaves the problem that the string may contain a newline character (not just whitespace) when using fgets. One must make annoying provisions for ends of lines that are not necessary when input is treated as a continuous stream of characters.


next up previous contents
Next: Source File organisation Up: Interactive Previous: Output   Contents
Tim Love 2010-04-27