c - sscanf 读入了错误的值

标签 c scanf

对 C 还很陌生,我正在尝试解析来自文件的输入。我在获取操作和地址字段时没有问题,但我在大小字段中获取值“32767”。

这是导致问题的代码:

#include <stdio.h>
#include <string.h>

void read_file(char *filename)
{
    // operation field, address field, size field 
    FILE *file = fopen(filename, "r");
    char buff[25];
    char operation;
    long address;
    int size;

    char *cur_trace = fgets(buff, 25, file);

    while (cur_trace) {
        // read indivdual fields of trace
        // if cur_trace[0] == I then ignore line
        if (cur_trace[0] != 'I') {
            sscanf(cur_trace, " %c %lx[^,]%*c%u", &operation, &address, &size);
            printf("operation: %c\n address: %lx\n size: %u\n", operation, address, size);
        }   
        cur_trace = fgets(buff, 25, file);
    }
}

int main(int argc, char const *argv[])
{
    read_file("tester.txt");
    return 0;
}

这是我正在阅读的输入文本。所有以“I”开头的行都将被忽略。

I 0400d7d4,8
 M 0421c7f0,4
 L 04f6b868,8
 S 7ff0005c8,8

最佳答案

括号不是格式字符串的通用部分,它是特定 scanf 的一部分格式化代码来读取字符串。它不能只是作为一种模式放置在任何地方,或用于任何其他格式。

顺便说一句,读取十六进制值将在第一个非十六进制字符处停止,因此您无论如何都不需要它。只是做例如

sscanf(cur_trace, " %c %lx,%u", &operation, &address, &size);

应该足够了(如果变量的类型是正确的)。

关于c - sscanf 读入了错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33952266/

相关文章:

c - 位掩码左移

c - 使用 scanf 存储字符串时出现问题

c - 从C中的txt文件中读取链表

c++ - 如何使用 sscanf 扫描由 `/` 分隔的两个字符串?

c - 在c中逐字读取缓冲区

c - 使用 icc 编译时我的程序无法正常运行

c - 是否在其绑定(bind)的未定义行为之外访问全局数组?

c - 从 C 中的文件读取矩阵无法按预期工作

c++ - Doxygen 包含图

c - Sscanf 没有以相同的方式读取相同的行