简体   繁体   English

如何为 sscanf 制作正确的格式

[英]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: 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 ).并且因为sscanf假设,是字符串的一部分而不是格式的一部分,所以根本不扫描 int(int output,它的0而不是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.如果到达那么远,请使用"%n"记录扫描的偏移量。

  • 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.考虑有关打印字符串以增加 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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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