c - 读入数组直到文件末尾

标签 c arrays file eof scanf

我一直在试图找出我错在哪里,但我似乎无法指出我的错误到底在哪里。

我正在尝试从我的文本文件中读取这些整数

5 2 4 9 10 1 8 13 12 6 3 7 11

到数组 A 中。为了确保它有效,我试图打印 A 但只得到大的随机数。有人可以帮我看看我哪里出错了吗?

int main(){

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

int A[100];

while(!feof(in)){
    fscanf(in, "%s", &A);
    printf("%d", A)
  }

 fclose(in);
 return 0;
}

*这只是与问题相关的代码的主要部分

最佳答案

对于所有真正了解为什么使用 feof 总是错误的人,解决方案类似于以下内容。该代码将打开作为程序第一个参数给出的文件名(或默认从 stdin 读取):

#include <stdio.h>

enum { MAXI = 100 };

int main (int argc, char **argv) {

    int i = 0, A[MAXI] = {0};   /* initialize variables */
    /* read from file specified as argument 1 (or stdin, default) */
    FILE *in = argc > 1 ? fopen (argv[1],"r") : stdin;

    if (!in) {  /* validate file opened for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    /* read each number from file or until array full */
    while (i < MAXI && fscanf (in, " %d", &A[i]) == 1)
        printf (" %d", A[i++]);
    putchar ('\n');

    if (in != stdin) fclose (in);

    printf ("\n '%d' numbers read from the file.\n\n", i);

    return 0;
}

示例使用/输出

使用文件 dat/myints.txt 中的示例值会产生以下结果:

$ ./bin/rdints dat/myints.txt
 5 2 4 9 10 1 8 13 12 6 3 7 11

 '13' numbers read from the file.

关于c - 读入数组直到文件末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36709333/

相关文章:

c - 是否可以修改函数内结构体指针的内容?

arrays - Pandas 列表列表中的一系列列表

c - 关于 C 中可变大小的数组

C - 从文本文件中读取字符串并按大小排列

c - 如何调整此代码以允许未指定数量的正整数

c - C 中的动态字符串输入

c - 在 C 循环中使用字符数组引用

python - 将数组从 C++ 返回到 Python

javascript - 读取二进制文件并从中生成一个字符串

javascript - 我如何在javascript中打开任何类型的文件并将其保存为字符串