Getting input in C

 

Contents


The scanf() function is the input method equivalent to the printf() output function - simple yet powerful. In its simplest invocation, the scanf format string holds a single placeholder representing the type of value that will be entered by the user. These placeholders are exactly the same as the printf() function - %d for ints, %f for floats, and %lf for doubles.

There is, however, one variation to scanf() as compared to printf(). The scanf() function requires the memory address of the variable to which you want to save the input value. While pointers are possible here, this is a concept that won't be approached until later in the text. Instead, the simple technique is to use the address-of operator, &. For now it may be best to consider this "magic" before we discuss pointers.

A typical application might be like this:

  #include <stdio.h>
  
  int main(void) 
  {
     int a;
     
     printf("Please input an integer value: ");
     scanf("%d", &a);
     
  } 
                                          


If you are trying to input a string using scanf, you should not include the & operator.

If you were to describe the effect of the scanf() function call above, it might read as: "Read in an integer from the user and store it at the address of variable a ".

Note of caution on inputs: When data is typed at a keyboard, the information does not go straight to the program that is running. It is first stored in what is known as a buffer - a small amount of memory reserved for the input source. Sometimes there will be data left in the buffer when the program wants to read from the input source, and the scanf() function will read this data instead of waiting for the user to type something. The function fflush(stdin) may fix this issue on some computers and with some compilers, by clearing or "flushing" the input buffer. But this isn't generally considered good practice and may not be portable - if you take your code to a different computer with a different compiler, your code may not work properly.

 


 

All text is available under the terms of the GNU Free Documentation License
Source : Wikibooks