简体   繁体   English

C,从文件读入数组,按数字编号

[英]C, read from file into array, number by number

void readfromFile() {

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

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

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

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

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

    fclose(myFile);
}

"matrikel.txt" contains “ matrikel.txt”包含

808098822790 

The number seems to be too long for the int numberArray[12] , when running the code it prints a random number. 该数字对于int numberArray[12]似乎太长,在运行代码时它会打印一个随机数。 When cutting some of the single integers from the end of the number it works, the maximum length seems to be 9. 从数字末尾切出某些单个整数时,最大长度似乎为9。

I'm not quite sure but shouldn't the fscanf in the first for loop print one single digit number into each cell of numberArray[] ? 我不太确定,但是第一个for循环中的fscanf是否不应该在numberArray[]每个单元格中打印一个数字?

A format specifier for scanf follows this prototype: %[*][width][length]specifier So, with %1d you will read a single number each time. 这个原型遵循scanf的格式说明符: %[*][width][length]specifier因此,使用%1d您每次都会读取一个数字。 But would be more simple to read each number as a char with fgetc(myFile); 但是使用fgetc(myFile);以char形式读取每个数字会更简单fgetc(myFile);

 for (i = 0; i < 12; i++) {
     int c = fgetc(myFile);
     if(c == EOF)
        break;
     numberArray[i] = c - '0';
 }

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

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