National Instruments 320682C Musical Toy Instrument User Manual


 
Chapter 2 Formatting and I/O Library
© National Instruments Corporation 2-63 LabWindows/CVI Standard Libraries
String to Integer and String
char *s;
char buf[10];
int a, n;
s = "32abc";
n = Scan (s, "%s>%i%s", &a, buf);
/* result: a = 32, buf = "abc", n = 2 */
s = "32abc";
n = Scan (s, "%s>%i %s", &a, buf);
/* result: a = 32, buf = ?????, n = 1 */
Remarks
After the first call to
Scan
,
a
= 32,
buf
=
"abc"
, and
n
= 2. Notice there are no spaces in the
format string between the two target specifiers. In the second call, there is a space between
%i
and
%s
. Consequently,
Scan
expects a space to occur in
s
immediately after the integer.
Because there is no space in
s
,
Scan
fails at that point. It leaves
buf
unmodified and returns 1
(indicating that only one target specifier is satisfied).
Note: Do not put spaces between specifiers in
Scan
,
ScanFile
, or
ScanIn
format strings.
String to Real, Skipping over Non-Numeric Characters in the String
char *s;
double x;
int n;
s = "VOLTS = 1.2";
n = Scan (s, "%s>%s[dt#]%f", &x); /* result: x = 1.2, n = 2 */
s = "VOLTS = 1.2";
n = Scan (s, "%s[i8]>%f", &x); /* result: x = 1.2, n = 1 */
s = "VOLTS = 1.2";
n = Scan (s, "%s>VOLTS = %f", &x); /* result: x = 1.2, n = 1 */
Remarks
The three different format strings represent different methods for skipping over non-numeric
characters. In the first call, the format string contains two target specifiers. In the first specifier
(
%s[dt#]
), the
t#
modifier instructs
Scan
to read bytes from
s
until a number is
encountered. The
d
modifier indicates that the bytes must be discarded because there is no
argument corresponding to the specifier. When the
Scan
call succeeds, it returns 2, indicating
that two target specifiers were satisfied, even though there is only one target argument.
In the second call, the source specifier
%s[i8]
instructs
Scan
to ignore the first 8 bytes of
s
.
This method works only if the location of the number within
s
is always the same.
In the third call, the format string contains the non-numeric characters literally. This method
works only if the non-numeric characters in
s
are always the same.