【问题标题】:How would I scan an integer value followed by a character using scanf in C如何在 C 中使用 scanf 扫描整数值后跟字符
【发布时间】:2017-10-25 05:17:42
【问题描述】:

所以我试图从文本文件中扫描 91h。到目前为止,我已经尝试使用 getchar 和 scanf 但它们都没有将整个 91h 扫描到声明的字符串。 我在这里缺少一个技巧吗?

【问题讨论】:

  • 请用一些代码sn-p详细说明
  • 您只是想将“91h”读入字符串缓冲区吗?或者“91”进入一个变量,然后“h”进入另一个变量?
  • "扫描整个 91h 到一个声明的字符串。"如果输入行是91h 使用char int_char[20]; scanf("%19s", int_char) 有什么问题?
  • 目的地的变量类型是什么?

标签: c char text-files scanf getchar


【解决方案1】:

这行得通:

#include <stdio.h>

int main()
{
    FILE *file = fopen("test.txt", "r");

    int x1 = 0;
    int x2 = 0;
    int x3 = 0;
    int x4 = 0;
    fscanf(file, "%xh %xh %xh %xh", &x1, &x2, &x3, &x4);

    printf("x1: %x, x2: %x, x3: %x, x4: %x\n", x1, x2, x3, x4);
}

文件test.txt中的测试数据:

91h 82h 93h 94h
91h 82h 93h 94h

【讨论】:

    【解决方案2】:

    如果您只是将它们读入缓冲区:

    char buff[128];
    (f)scanf(file, "%s", buff);
    

    如果您将它们读入 2 个单独的变量:

    int num;
    char var;
    (f)scanf("%2d%c", &num, &var);
    

    【讨论】:

    • 这不适用于例如9Ah,尽管问题的意图尚不清楚。
    • 有了他的输入就可以了。但他想要什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 2021-05-10
    相关资源
    最近更新 更多