C - sscanf 在读取文件后给我错误的输出

标签 c file struct delimiter scanf

我试图从 C 中的文本文件中读取一行,但是输出表示错误。我想我在我的代码中做错了分隔符。有人可以帮忙吗?

正文:

hello, world, 1, 2, bye

输出:

hello world 12576 117453344 bye

typedef struct structure {
    char hello[25];
    char world[25];
    int num1;
    int num2;
    char bye[25];
} Hello;

主要内容:

#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include "structure.h"

using namespace std;

int main(int argc, char **argv) {
    char line[25];
    FILE *fp;
    fp = fopen("text.txt", "r");
    Hello c;  

    while (fgets(line, sizeof(line), fp) != NULL) {
        sscanf(line, "%[^','],%[^','],%[^','],%[^','],%s",
               c.hello, c.world, &c.num1, &c.num2, c.bye);
    }

    printf("%s %s %d %d %s", c.hello, c.world, &c.num1, &c.num2, c.bye);   

    return 0;
}

最佳答案

不要使用 %[^','] 读取整数。 %d 应该被使用并且也只是忽略 ',' 在字符串中使用说明符 %[^,]sscanf

并检查它的返回值。

关于C - sscanf 在读取文件后给我错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35523013/

相关文章:

c++ - 从源代码中提取预处理器符号

c - 我在 C 的输出中收到未知字符

将最大堆转换为二叉搜索树

c++ - 按不同字段对结构队列进行排序

c - 不使用 typedef 重写结构体

有限素数域中代数的 C 代码片段

java - PDF 专用文件浏览器

mysql - 二进制字段,Waterline ORM

c# - 以编程方式为 C# 中的文件添加安全权限

c++ - 不允许将结构实例分配给类实例