【问题标题】:Why does my fscanf seem to not read anything?为什么我的 fscanf 似乎什么也没读?
【发布时间】:2019-11-27 12:29:20
【问题描述】:

我正在尝试用 C 语言编写一个程序,用于从文件中读取文本行,并创建节点来构建树。这些节点是结构。为此,我尝试一次阅读六行。但是,每当我的程序到达 fscanf 行时,它似乎什么都没有读取,将我的 int 设置为 EOF 并退出该函数。我尝试了很多格式组合,删除和添加空格,\n 等。我什至尝试制作一个单独的 fscanf 行来尝试读取单个字符串,即使这样似乎什么也没扫描。我不知道为什么会这样。这是相关代码:

member_ptr readAndCreate(FILE * file){
    member_node * temp;
    temp = calloc(1, sizeof(member_node));
    //char temp_char_array[50] = {0,0,0,0,0};
    //char *overflow;

    int isEnd;
    //isEnd = fscanf(file, " %s", temp_char_array);

    //isEnd =
    isEnd = fscanf(file, " %[^\n] %[^\n] %d %[^\n] %[^\n] %[^\n]",
            temp -> family,
            temp -> personal,
            &temp ->ID,
            temp -> email,
            temp -> boatClass,
            temp -> boatName
            );

    //temp->ID =  (int)strtol(temp_char_array, &overflow, 10);
    if (isEnd == EOF){
        printf("Something went wrong, please try again \n");
        return NULL;
    } else {
        return temp;
    }
}

这是主要功能

int main() {
    char pathname[100];
    FILE * file;
    member_ptr top;
    member_ptr temp;

    printf("input file path\n");
    scanf("%[^\n]", pathname);
    file = fopen(pathname, "r");

    if (file == NULL){
        printf("file cannot be found, closing program...");
        exit(1);
    }

    top = readAndCreate(file);
    genTree(top, file);
    printOutTree(top);

    printf("Hello, World!\n");
    return 0;
}

【问题讨论】:

  • 这不能被编译来测试它并且我们没有你正在使用的输入文件,但是我没有发现任何明显的错误。一种可能性是由于输入,例如,文件格式错误或行太长,导致未定义的行为,因为您没有限制正在读取的字符串的长度。我还建议用perror("fscanf") 替换“出了问题”printf。请参阅stackoverflow.com/help/minimal-reproducible-example
  • scanf 家族函数只是穷人的解析器。我尽量不将它们用于复杂或严肃的处理,并且从不用于面向行的输入。由于您的输入是面向行的,fgets 将是一个更可靠的选择
  • 发布member_node的定义,。 minimal reproducible example 更好。
  • scanf 对于“玩具”程序来说几乎没有问题,而对于真正的程序则根本不行。经验法则:如果您发现自己在使用%[...],是时候放弃scanflearn how to use something better。从长远来看,它会更实用并且更容易。
  • 请做一个 MRE,问题可以例如很容易在 genTree 中。

标签: c scanf


【解决方案1】:

我发现您的扫描码有问题。 s 指定字符串输入似乎丢失了。

尝试改变

isEnd = fscanf(file, " %[^\n] %[^\n] %d %[^\n] %[^\n] %[^\n]",

进入

isEnd = fscanf(file, " %[^\n]s %[^\n]s %d %[^\n]s %[^\n]s %[^\n]s",

main() 函数中存在相同的错误。

【讨论】:

    猜你喜欢
    • 2014-12-18
    • 1970-01-01
    • 2021-07-07
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    相关资源
    最近更新 更多