It is possible to use scanf() to read in two numbers from a single line of input. This requires that scanf()' s conversion specification be modified to specify two conversions and also that the addresses to store both numbers be supplied as parameters to the scanf() function. A sum of two numbers program that works this way is shown below.
/* Another sum of two numbers
program
*/
main()
{
int n1;
int n2;
printf("Enter two numbers ");
scanf("%d%d",&n1,&n2);
printf("The sum is %d\n",n1+n2);
}
Several runs of the program are shown below. The dollar symbol (
$
) is the operating system (Unix) prompt.
sum2
is the name of the file holding the executable version of the program. $ sum2 Enter two numbers 11 4 The sum is 15 $ sum2 Enter two numbers 21 73 The sum is 94 $ sum2 Enter two numbers 44 -10 The sum is 34 $ sum2 Enter two numbers 23 11 The sum is 34Although the conversion specification is %d%d suggesting that the numbers should be concatenated, scanf() will accept numbers with arbitrary intermediate space and will, in fact, not accept concatenated numbers. This works because scanf(), when using d conversion rules, accepts an arbitrary amount of leading space. As far as scanf() is concerned a space is generated by the user hitting the SPACE bar, the TAB key or the RETURN key.
The final example is particularly interesting showing a slightly peculiar feature of the operation of scanf(). The user had hit the keys 2 and 3 and then hit the RETURN key. scanf(), quite properly, assumed that the first number the user had entered was 23 but the input specification required two decimal numbers so scanf() carried on reading input until it had obtained another number. The user could have hit RETURN many times before typing 11 and the program would have produced the same result.
You will also notice that scanf(), not surprisingly, is quite happy with negative numbers.