Keil™, An ARM® Company

Discussion Forum

sscanf does not work properly

Next Thread | Thread List | Previous Thread Start a Thread | Settings

DetailsMessage
Read-Only
Author
Mike Kleshov
Posted
9-Mar-2002 09:26
Toolset
C166
New! sscanf does not work properly
I started to use the sscanf function to parse commands from serial port and found out that it does not work as it must do. Example:
int i, j = 0x1234;
char c = '\0';
i = sscanf("anything", "%d%c", &j, &c);
After the function call:
i == 1,
j == 0,
c == 'a',
while there should have been:
i == 0,
j == 0x1234,
c == '\0'.

Obviously, I cannot detect some errors in the input with this 'non-ANSI' sscanf. Does anyone have any ideas how to solve the problem?
Read-Only
Author
Dan Henry
Posted
9-Mar-2002 10:55
Toolset
C166
New! RE: sscanf does not work properly
Since sscanf() does not appear to be returning after the first conversion (matching) failure, you might want to consider using the strtol() or strtoul() functions to convert the integer portions of the strings. These functions provide extra "feedback" about the progress of their conversions.
Read-Only
Author
Mike Kleshov
Posted
10-Mar-2002 12:49
Toolset
C166
New! RE: sscanf does not work properly
As soon as I read my own question the answer came to me :-) I can detect errors in the input by checking if the c field has been modified by sscanf (since I cannot rely on the return value).
It will do as a workaround. Clearly there is an error in the implementation of a library function. Hopefully, Keil Software will fix that soon.
Read-Only
Author
Mark Odell
Posted
11-Mar-2002 09:41
Toolset
C166
New! RE: sscanf does not work properly
Just a comment, scanf() is a notoriously dangerous function, even for experts. Best to fgets() the line and parse it out safely in memory.

- Mark
Read-Only
Author
Jon Ward
Posted
11-Mar-2002 18:43
Toolset
C166
New! RE: sscanf does not work properly
What version of C51 are you using?

Jon
Read-Only
Author
Mike Kleshov
Posted
12-Mar-2002 04:57
Toolset
C166
New! RE: sscanf does not work properly
It's C166, latest version.

Next Thread | Thread List | Previous Thread Start a Thread | Settings