In the C programming language there is a special function called scanf
that reads input from the terminal. For example, the statement:
scanf("%d", &count);
reads an integer value from the keyboard and puts that value in the variable
count. Take a look at the above statement and you might notice some
similarities between the scanf function and the printf function
that we previously discussed. In what ways do you think these two functions
might be alike?
Click here for a list of similarities.
scanf looks for the special ``%d'' and ``%f'' sequences in
the control string, which tell scanf to read integers and floating point
numbers respectively. Take a look at the sample program ``joints.c''
and locate the line:
scanf("%f", &theta_degrees);
What does that statement do?
Click here for the answer.
The control string that you give to scanf should be exactly ``%d''
if you want to read an integer, or ``%f'' if you want to read a floating
point number.
Finally, you might have noticed something unusual in the scanf statements
that we've been looking at. What is that?
Click here for the answer.
When you use scanf you must put an ampersand before the name of
the variable that you want to read into. It is absolutely required!
Unfortunately it is also easy to forget. Even expert C programmers forget it
sometimes.
So what does that ampersand do? At this point in your study of C, it's not
easy to explain. For now just remember that it has to go before the name of
the variable.
Eric N. Eide
Hamlet Project
Department of Computer Science
University of Utah