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

Chapter 5 301
HP C/iX Library Function Descriptions
scanf
multiple spaces between items and varying identifying strings (that is, "PROFESSION:"
could be specified instead of "PROF:"). The following scanf() call reads the same data, but
is much less flexible:
scanf("NAME: %[^;]; AGE:%d; PROF: %[^;]; SAL: %d",name,&age,prof,&salary);
In this example, literal characters are used to exactly match the characters in the input
line. This only works if you can be sure that the data always appears in this form.
However, if a typing variation is made, such as typing "SALARY:" instead of "SAL:", the
scanf() fails.
Scanf() waits for more data as long as there are unsatisfied conversion specifications in
the format. Thus, the scanf() call
scanf(“%f%f%f”, &float1, &float2, &float3);
where float1, float2, and float3 are all variables of type float, allows you to enter
data in several ways. For example,
14.77 29.8 13.0
is read correctly by scanf(), as is
14.77
29.8
13.0
Using decimal points in floating-point data is recommended whenever floating-point
variables are being read. However, scanf() converts integer data to floating-point if the
conversion specification so demands. Thus, "13.0" in the previous example could have been
entered as "13" with no side effects.
As a final example, consider the input string:
abcdef137 d14.77ghijklmnop
Suppose the following code fragment is used to read this string:
char arr1[10], arr2[10], arr3[10], arr4[10];
float float1;
scanf("%4c%[^3]%6c%f%[ghijkl]",arr1,arr2,arr3,&float1,arr4);
%4c Reads four characters and assigns them to arr1. Thus, the string abcd is
assigned to arr1. Note that a null character is not appended to the end of
the string.
%[ ^ 3] Reads all characters from the current character up to the character 3.
This assigns ef1, along with an added null character, to the array arr2.
%6c Reads the next six characters and stores them in the array
arr3.
Thus, 37
d14 is assigned to arr3. A null character is not appended to the end of the
string.
%f Reads a floating-point value which, due to the lack of a field width, is
terminated by the first inappropriate character. Thus, the value .77 is
assigned to float1.
%[ghijkl] Reads all characters up to the first character not occurring between the
brackets. This stores the string ghijkl, along with an appended null