ARM Technical Support Knowledge Articles

SSCANF RETURNS INCORRECT NUMBER OF PARAMETERS SCANNED

Applies to: C51 C Compiler

Answer


Information in this article applies to:


QUESTION

I'm using the sscanf function in my program and the return value (the number of parameters scanned) is incorrect. The following example program demonstrates this problem:

#include <stdio.h>
#include <string.h>
#include <reg51.h>

int main(void)
{
char buf[100];
int scanned;
unsigned long addr;
unsigned int value;

SCON  = 0x50;  /* SCON: mode 1, 8-bit UART, enable rcvr      */
TMOD |= 0x20;  /* TMOD: timer 1, mode 2, 8-bit reload        */
TH1   = 221;   /* TH1:  reload value for 1200 baud @ 16MHz   */
TR1   = 1;     /* TR1:  timer 1 run                          */
TI    = 1;     /* TI:   set TI to send first char of UART    */

strcpy (buf, "1234 1234");
scanned = sscanf(buf, "%lu %u", &addr, &value);
printf("Number of parameters scanned (from %s): %d\n", buf, scanned);

strcpy (buf, "1234");
scanned = sscanf(buf, "%lu %u", &addr, &value);
printf("Number of parameters scanned (from %s): %d\n", buf, scanned);

while(1);
}

The number of parameters that are reported scanned in each case is 2 and this is incorrect. The reported number of parameters should be 2 and 1.

ANSWER

This is a problem in the scanf library function provided with C51 V6.14. It is corrected in C51 V6.20 (and later versions). You may download the latest updates from the Keil Website.

As a work-around, add a space character to the end of the scanf buffer. For example:

strcpy (buf, "1234 ");
scanned = sscanf(buf, "%lu %u", &addr, &value);
printf("Number of parameters scanned (from %s): %d\n", buf, scanned);

generates the correct number of scanned parameters.

ATTACHED FILES

Request the files attached to this knowledgebase article.

Article last edited on: 2005-06-03 18:46:25

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential