Why do the FSCANF and SSCANF functions not work as expected with the %i and %d format specifiers?

4 views (last 30 days)
There appears to be problems using the SSCANF function and the FSCANF function with the %d and %i format specifiers. The following output at the MATLAB command prompt illustrates this problem:
sscanf('0008','%4d') % works as expected
ans =
8
sscanf('2.34','%4d') %does not work as expected
ans =
''
sscanf('0008','%4i') %does no work as expected
ans =
''
sscanf('8','%4i') %this works as expected
ans =
8

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
The above behavior of the FSCANF and SSCANF functions are the expected behavior. Note that the two cases that seemingly do not work as expected actually return "silent" errors. You can view these errors if you call the SSCANF function with 4 output arguments and look at the ERRMSG output.
[A,COUNT,ERRMSG,NEXTINDEX] = SSCANF(S,FORMAT,SIZE)
The problem in the first case occurs because it is not acceptable to pass digits containing a decimal point as input to be scanned by %d (which takes a base10 integer).
[a,count,errmsg,nextidx]=sscanf('2.34','%3d') % decimal point
a = ''
count = 0
errmsg = Matching failure in format.
nextidx = 1
The second problem occurs because the %i refers to a base10 integer by default, unless the numeric value begins with 0x or 0X (zero x), in which case it is a base16 (hex) integer and if it begins with a 0 (zero) then it is a base8 (octal) integer.
[a,count,errmsg,nextidx]=sscanf('08','%4i') % octal digits are 0-7.
a = ''
count = 0
errmsg = Matching failure in format.
nextidx = 1
The above code caused an error because 8 is not a valid octal digit.

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!