| C Programming Simple input | Operators and type casting |
Now that we can create variables, let's learn how to fill those variables with input from the user. Like the output functions fromSimple output, these input functions are declared instdio.h, part of the C standard library.
scanf()Thescanf() function is the input method equivalent to theprintf() output function. In its simplest invocation, the scanfformat string holds a singleplaceholder representing the type of value that will be entered by the user. These placeholders are mostly the same as theprintf() function -%d for integers,%f for floats, and%lf for doubles.
There is, however, one variation toscanf() as compared toprintf(). Thescanf() function requires the memory address of the variable to which you want to save the input value. Whilepointers (variables storing memory addresses) can be used here, this is a concept that won't be approached until later in the text. Instead, the simple technique is to use theaddress-of operator,&. For now it may be best to consider this "magic" before we discusspointers.
A typical application might be like this:
#include<stdio.h>intmain(void){inta;printf("Please input an integer value: ");scanf("%d",&a);printf("You entered: %d\n",a);return0;} |
If you were to describe the effect of thescanf() function call above, it might read as: "Read in an integer from the user and store it at the address of variablea".
fgets()To read strings, use a different function,fgets(), like this:
#include<stdio.h>intmain(void){charname[40];printf("Please input your name: ");fgets(name,sizeof(name),stdin);printf("You entered: %s\n",name);return0;} |
fgets() has three parameters: a string to read into (name), the maximum size of the string (sizeof(name)), and astream to read from (stdin).
Don't worry about streams for now—they will be covered ina later chapter. For now, know thatstdin refers to astream of characters the user is inputting to your program. |
We givefgets() a maximum size so that, if the user types more characters than there is room for in the string, the input doesn't go past the end ofname in memory and overwrite unrelated data. This is abuffer overflow. Thankfully, because we set the maximum size correctly, this doesn't happen, and any additional characters instead stay in thestream, waiting to be read by future calls tofgets() orscanf().
The size we give tofgets() is a maximum size, not a guaranteed size.fgets() stops reading when the user presses↵ Enter.
The example above could also be accomplished with
Pre-C11 versions of the C standard had featured |
| C Programming Simple input | Operators and type casting |