Chapter 3
Getting Input with scanf()
The scanf() function is used to read data from the standard input
stream (stdin) and store that data in program variables
By default, the stdin stream is associated with the keyboard
The input data is read according to a specified format, very similar
to the way that output is handled with printf()
The scanf() function accepts a variety of parameters:
scanf(%d, &i);
The first one is a format string enclosed in double quotes ""
The next parameters are the memory addresses of the variables
in which the input data will be stored
The number of conversion specifiers included in the format string
should equal the number of variables, and the type of each specifier
should match the data type of the respective variable
The conversion characters used in scanf() are the same as those used
in printf() (e.g., the %d specifier is used to read an int, while %f is
used to read a float, etc).
ATTENTION!!! The %lf specifier (and not %f) is used to read a double
item that does not match the type of the conversion specifier
Exercise
#include <stdio.h>
int main()
{
int i;
float j, sum;
printf("Enter numbers: ");
scanf("%d%f", &i, &j);
sum = i+j;
printf("%f\n", 3*sum);
return 0;
}
Comments: There is no need to declare the variable sum. Instead,
we could write printf("%f\n", 3*(i+j));
C: From Theory to Practice Chapter 3
Sample input:
1 -20 .3 -4.0e3
10
11
12
13
14
15
16
17
18
addfrac.c
/* Adds two fractions */
#include <stdio.h>
int main(void)
{
int num1, denom1, num2, denom2, result_num, result_denom;
printf("Enter first fraction: ");
scanf("%d/%d", &num1, &denom1);
printf("Enter second fraction: ");
scanf("%d/%d", &num2, &denom2);
result_num = num1 * denom2 + num2 *denom1;
result_denom = denom1 * denom2;
printf("The sum is %d/%d\n",result_num, result_denom)
return 0;
}
Copyright 2008 W. W. Norton &
Company.
All rights reserved.
19