首页 > 解决方案 > 如何使用 fscanf() 扫描宽度 = 2 的 UINT?

问题描述

我需要读取像“01”这样的数据,但跳过像“1”这样的数据。我试过fscanf(f, "%2lu ", &ulong)了,但似乎 2 是最大长度,不是固定的。

是的,我知道我可以用 %c%c 之类的符号来做到这一点,但是阅读代码会更难。

我应该怎么办?

标签: c++cformatscanf

解决方案


使用"%n"转换说明符

#include <stdio.h>

int main(void) {
    long n;
    int m1, m2;
    if (sscanf("   123\n", " %n%ld%n", &m1, &n, &m2) != 1) puts("scanf error");
    if (m2 - m1 != 2) puts("error with 123");
    if (sscanf("   12\n", " %n%ld%n", &m1, &n, &m2) != 1) puts("scanf error");
    if (m2 - m1 != 2) puts("error with 12");
    if (sscanf("   1\n", " %n%ld%n", &m1, &n, &m2) != 1) puts("scanf error");
    if (m2 - m1 != 2) puts("error with 1");
    return 0;
}

更好的是:永远不要scanf()用于用户输入。


推荐阅读