fscanf 功能出现问题

问题描述 投票:0回答:1

我无法让这个功能正常工作。它在 for 循环处崩溃。我只发布摘录和变量。

我尝试将

hurricanes[i]
states[i]
更改为
&hurricanes[i]
&states[i]
。程序运行,但仅将起始字母保存到数组中。

这是所读取文件的摘录。

2005 Katrina LA
int years[NUM_HURRICANES] = {0};

    char    hurricanes[NUM_HURRICANES][100] = {0},
            states[NUM_HURRICANES][5] = {0};

void file_handling(int *years, char *hurricanes, char *states)
{
    //File handling
    FILE *file_ptr;

    //accesing the file
    if ((file_ptr = fopen("hurricanes.txt", "r")) == NULL)
        puts("File not found.");
    else
        puts("File found.");

    //load the data into the arrays
    for(int i = 0; i < NUM_HURRICANES; i++)
        fscanf(file_ptr, "%d %s %s", &years[i], hurricanes[i], states[i]);

    fclose(file_ptr);
}
arrays c
1个回答
0
投票

你有全局变量。您不需要将它们作为函数参数传递来访问它们。这就是拥有全局变量的全部意义。

以下是如何使用全局变量构建代码:

文件:飓风.txt

2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA

文件:main.c

#define NUM_HURRICANES 10
#include <stdio.h>
#include <stdlib.h>

static int years[NUM_HURRICANES] = {0};
static char hurricanes[NUM_HURRICANES][100] = {0}; 
static char states[NUM_HURRICANES][5] = {0};

void file_handling(void) {
    
    FILE *file_ptr;

    if ((file_ptr = fopen("hurricanes.txt", "r")) == NULL) {
        puts("File not found.");
        exit(1);
    } else puts("File found.");

    for(int i = 0; i < NUM_HURRICANES; i++) {
        fscanf(file_ptr, "%d %s %s", &years[i], hurricanes[i], states[i]);
        printf("%d %s %s\n", years[i], hurricanes[i], states[i]);
    }

    fclose(file_ptr);
}

int main(void) {
    file_handling();
    return 0;
}

标准输出:

File found.
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA
2005 Katrina LA

我无法说出为什么你的代码崩溃。因为你显然没有分享导致崩溃的原因。

© www.soinside.com 2019 - 2024. All rights reserved.