KnowledgeBase Archive

An Archive of Early Microsoft KnowledgeBase Articles

View on GitHub

Q67790: %n Format Specifier May Be Ignored in C 6.00 sscanf()

Article: Q67790
Product(s): See article
Version(s): 6.00 6.00a | 6.00 6.00a
Operating System(s): MS-DOS | OS/2
Keyword(s): ENDUSER | | mspl13_c
Last Modified: 6-FEB-1991

If the "%n" format specifier is used within a sscanf() function and
the format specifier before it causes the last character to be read
from the string of data, the %n will be ignored and the sscanf()
function will return without making the %n assignment. This is correct
per ANSI specifications, since an input failure before the %n
parameter is evaluated.

The code below demonstrates the problem. Notice that the last
parameter passed (d) does not get changed. The sscanf() statement
finishes making assignments as soon as it reaches the end of the
string.

Sample Code
-----------

#include <stdio.h>

void main(void)
{
   int a,b,c,d;
   char buffer[50];
   a=b=c=d=0;

   sscanf("100Dummy2","%n%d%n%s%n",&a,&b,&c,buffer,&d);

   printf("%d  %d  %d\n",a,c,d);
}

Output
------

0  3  0

THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Copyright Microsoft Corporation 1986-2002.