HP C/iX Library Reference Manual (30026-90004)
300 Chapter5
HP C/iX Library Function Descriptions
scanf
("NAME:"). To read the strings, first note that the identifying strings are always delimited
by space characters. This suggests use of the s conversion character to read them. Second,
you can never know the exact sizes of the NAME and PROF fields, but note that they are
both terminated by a semicolon. Thus, you can use [ to read them. Finally, the d
conversion character can be used to read both integers. (Note: On 16-bit processors, you
probably need to use a long int to read the salaries. Thus, ld should be used instead of
d.)
The following code fragment successfully reads this data:
char name[40], prof[40];
int age;
long int salary;
.
.
scanf("%*s%*[ ]%[^;]%*c%*s%d%*c%*s%*[ ]%[^;]%*c%*s%ld",name,&age,
prof,&salary);
For easier understanding, break the format into pieces:
%*s This reads the string "NAME:". Since an asterisk is given the string is
simply read and discarded.
%*[ ] This removes all blanks occurring between "NAME:" and the employee's
name. Note that this removes one or more blanks, giving the format some
flexibility.
%[^;] This reads all characters from the current character up to a semicolon, and
assigns the characters to the array name.
%*c This removes the semicolon left over after reading the name.
%*s This reads the next identifying string, "AGE:", and discards it.
%d This reads the integer age given, and assigns it to age. The semicolon
after the age terminates %d, because that character is not appropriate for
an integer value. Note that the address of age is given in the item list ()
instead of the variable name itself. If this is not done, a memory fault
occurs at runtime due to the attempt of scanf() to use the parameter as a
pointer.
%*c This removes the semicolon following the age.
%*s This reads the next identifying string, "PROF:", and discards it.
%*[ ] This removes all blanks between "PROF:" and the next string.
%[^;] This reads all characters up to the next semicolon, and assigns them to the
character array prof.
%*c This removes the semicolon following the profession string.
%*s This reads the final identifying string, "SAL:", and discards it.
%ld This reads the final integer and assigns it to the long integer variable
salary. Again, note that the address of salary is given, not the variable
name itself.
Although somewhat confusing to read, this format is quite flexible, because it allows for