HP C/iX Library Reference Manual (30026-90004)

Chapter 5 329
HP C/iX Library Function Descriptions
sscanf
Examples
The following program reads a string from stdin, stores the string in the character array
string, and prints the first word of the string.
#include <stdio.h>
main()
{
char string[80], word[25], *gets();
/* get the string */
printf("Enter your string: ");
gets(string);
/* get the first word */
sscanf(string, "%s", word);
printf("The first word is %s.\n", word);
}
The sscanf() function is often used to convert ASCII characters into other forms, such as
integer or floating-point values. For example, the following program uses sscanf() to
implement a five-function calculator:
#include <stdio.h>
main()
{
char line[80], *gets(), op[4];
long n1, n2;
double arg1, arg2;
/* print prompt (>) and get input */
printf("\n> ");
gets(line);
/* begin loop */
while(line[0] != 'q') {
sscanf(line, "%*s%s", op);
if(op[0] == '+') {
printf("Answer: %g\n\n", arg1+arg2);
} else if(op[0] == '-') {
printf("Answer: %g\n\n", arg1-arg2);
} else if(op[0] == '*') {
printf("Answer: %g\n\n", arg1*arg2);
} else if(op[0] == '/') {
printf("Answer: %g\n\n", arg1/arg2);
} else if(op[0] == '%') {