HP C/iX Library Reference Manual (30026-90004)
330 Chapter5
HP C/iX Library Function Descriptions
sscanf
while(n1 >= n2)
n1 -= n2;
printf("Answer: %ld\n\n", n1);
} else
printf("Can't recognize operator: %s\n\n", op);
printf("> ");
gets(line);
}
}
The calculator program above accepts input lines having the form
value operator value
where
value
is any number, and
operator
is the symbol +,
-, *, /, or %, representing addition, subtraction, multiplication, division, or remainder,
respectively. All functions, except for the remainder function, are performed in
floating-point values; values for these functions can be entered with or without a decimal
point. Values for the remainder function must not have a decimal point. There must be at
least one space between each value and the operator.
Note that in this program, the entire input line is read using gets(). Then, the different
parts of the input line are read from line using sscanf(). The input line is stored as an
ASCII string in line, but portions are converted to floating-point or integer values,
depending on the operator.
Examples of valid entries are
15.778 * 3.89
27%8
17 + 39.72
The program terminates when it reads a line beginning with the letter "q", such as "quit".
There are two differences between reading data from stdin and reading data from a
string. First, reading data from stdin causes that data to no longer remain in stdin. This
is not true for a string. Because the data is stored in a string, the data remains in memory,
even if that data has been read several times. Second, because the data read from stdin
disappears as you read it, the next read operation from stdin always begins when the
previous read operation is terminated. This is not true when you read from a string using
sscanf().
Each successive read operation starts at the beginning of the string. Thus, if you want to
read five words from a string stored in a character array, you must read the words in a
single sscanf() call. If you try to read one word in five separate sscanf() calls, each call
starts reading at the beginning of the string and so you read the same word five times.
See Also
getc(), setlocale(), printf(), strtod(), strtol(), ANSI C 4.9.6.6, POSIX.1 8.1