简体   繁体   中英

How to make proper format for sscanf

In this code:

#include <stdio.h>

int main()
{
        char str[255];
        int val;

        sscanf("(abcd, 10)", "(%s, %d)", str, &val);
        printf("string: %s; int: %d\n", str, val);
}

the comma , is not recognized in format, but as part of the string being scanned. The output:

string: abcd,; int: 0

And because sscanf assume , to be part of string and not the format, the int is not scanned at all (int the output, its 0 instead of 10 ). So how to make scanner consider , as part of format, not string?

... how to make scanner consider, as part of format, not string?

  • Use "%[]" to selectively scan text.

  • Use a width to prevent buffer overflow.

  • Use "%n" to record the offset of the scan, if it got that far.

  • Consider " " to allow white-space in non-critical places.

  • Test for potential errors.

  • Consider sentinels about printing a string to add clarity to the output.

    // sscanf("(abcd, 10)", "(%s, %d)", str, &val);
    int n = 0; 
    //                v------v scan up to 254 (1 less than buffer size) non-comma characters.
    sscanf(input, " ( %254[^,],%d ) %n", str, &val, &n);
    if (n == 0 || input[n]) {
      fprintf(Stderr, "Scan failed or extra junk at the end.\n");
    } else {
      printf("string: \"%s\"; int: %d\n", str, val);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM