【问题标题】:How to scan UINT with width = 2 with fscanf()?如何使用 fscanf() 扫描宽度 = 2 的 UINT?
【发布时间】:2021-09-04 08:01:51
【问题描述】:

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

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

我该怎么办?

【问题讨论】:

  • 如果你有unsigned long ulong,那么fscanf(f, "%lu", &ulong);
  • 读取一个字符串(fgets(buf, sizeof buf, stdin)),检查它的长度(strlen(buf) > 2)和内容(if (isdigit((unsigned char)buf[0]) && isdigit((unsigned char)buf[1]))),...
  • 不要使用fscanf。用fgets读取字符串,然后手动解析。
  • @WeatherVane 好的,谢谢,但问题仍然存在
  • 但是的问题是什么?请显示输入、输出和预期输出,以及Minimal Reproducible Example,最短的完整代码,显示您尝试过的内容。

标签: c++ c format scanf


【解决方案1】:

使用"%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() 进行用户输入。

【讨论】:

  • 更改代码以使用前导空格,检查 scanf 的返回值
  • 好像这个数字也包含 %n 个字符
猜你喜欢
  • 2018-06-20
  • 1970-01-01
  • 2012-07-14
  • 2016-05-04
  • 1970-01-01
  • 2021-05-12
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多