将文本文件中的数字读入C中的数组

Von*_*nti 26 c arrays file scanf

我是编程菜鸟所以请耐心等待.

我正在尝试将文本文件中的数字读入数组.文本文件"somenumbers.txt"只包含16个数字,如此"5623125698541159".

#include <stdio.h>
main()
{

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

    //read file into array
    int numberArray[16];
    int i;

    for (i = 0; i < 16; i++)
    {
        fscanf(myFile, "%d", &numberArray[i]);
    }

    for (i = 0; i < 16; i++)
    {
        printf("Number is: %d\n\n", numberArray[i]);
    }


}
Run Code Online (Sandbox Code Playgroud)

该计划不起作用.它汇编但输出:

编号是:-104204697

数字是:0

编号是:4200704

编号是:2686672

编号是:2686728

编号是:2686916

编号是:2004716757

编号是:1321049414

数字是:-2

编号是:2004619618

编号是:2004966340

编号是:4200704

编号是:2686868

编号是:4200798

编号是:4200704

编号是:8727656

进程返回20(0x14)执行时间:0.118秒按任意键继续.

BLU*_*IXY 28

改成

fscanf(myFile, "%1d", &numberArray[i]);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这行得通,但是您能否解释一下%1d中的1确实发生了什么。例如,`%2d`不起作用。另外,我还有另一个文件,它有16个数字,但每个数字都用逗号分隔。我以为`fscanf(myFile,“%d,”,&numberArray [i]);`可以工作,但是不行。你能帮我吗? (2认同)
  • @Vonti`"%1d"``1`:读取fileld的最大大小.我认为它可能是一个"%d",如果你用逗号分隔的话. (2认同)

hac*_*cks 12

5623125698541159被视为单个数字(超出int大多数架构的范围).您需要在文件中写入数字

5 6 2 3 1 2 5  6 9 8 5 4 1 1 5 9  
Run Code Online (Sandbox Code Playgroud)

16个数字.

如果您的文件有输入

5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9 
Run Code Online (Sandbox Code Playgroud)

然后改变%d你的符fscanf%d,.

  fscanf(myFile, "%d,", &numberArray[i] );  
Run Code Online (Sandbox Code Playgroud)

经过一些修改后,您的完整代码如下:

#include <stdio.h>
#include <stdlib.h>

int main(){

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

    //read file into array
    int numberArray[16];
    int i;

    if (myFile == NULL){
        printf("Error Reading File\n");
        exit (0);
    }

    for (i = 0; i < 16; i++){
        fscanf(myFile, "%d,", &numberArray[i] );
    }

    for (i = 0; i < 16; i++){
        printf("Number is: %d\n\n", numberArray[i]);
    }

    fclose(myFile);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)