繁体   English   中英

我正在尝试编写一个C程序来将文件中的整数存储到数组中,但是它不起作用。 有人能帮我吗?

[英]I'm trying to write a C program to store integers from a file into an array, but it doesn't work. Can someone help me?

似乎我不太了解文件流的工作原理。 我的文本文件现在包含以下整数: 1 10 5 4 2 3 -6 ,但是我希望该程序能够更改文件中的任意数量的整数。

显然我什至没有使用正确的功能。 我编写的代码如下:

 int main() {
     printf("This program stores numbers from numeri.txt into an array.\n\n");
     int a[100];
     int num;
     int count = 0;

     FILE* numeri = fopen("numeri.txt", "r");

     while (!feof(numeri)) {
         num = getw(numeri);
         a[count] = num;
         if (fgetc(numeri) != ' ')
             count++;
     }

     int i;
     for (i = 0; i < count; i++) { printf("%d ", a[i]); }

     return 0;
}

我希望它打印出带有存储数字的数组,但我得到的只是: 540287029 757084960 -1

有人可以帮助我理解我做错了什么,也许告诉我如何正确编写这种代码?

我已经根据注释修复了您的代码。 我使用fscanf来读取文件,并通过检查count < 100并检查fscanf是否正好填充了一个参数来限制可以存储在数组中的数字量。

另外,为了安全起见,我检查了是否可以打开文件。 如果无法打开,则仅打印错误消息并return 1

int main() {

    printf("This program stores numbers from numeri.txt into an array.\n\n");
    int a[100] = {0};
    int num;
    int count = 0;
    int i = 0;

    FILE* numeri = fopen("numeri.txt", "r");
    if (numeri == NULL) {
        printf("Can't open file\n");
        return 1;
    }

    while (count < 100 && fscanf(numeri, "%d", &num) == 1) {
       a[count++] = num;
    }

    for (i = 0; i < count; i++) { printf("%d ", a[i]); }

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM