Reading numbers from a text file into an array in C

后端 未结 5 689
囚心锁ツ
囚心锁ツ 2020-11-30 05:00

I\'m a programming noob so please bear with me.

I\'m trying to read numbers from a text file into an array. The text file, \"somenumbers.txt\" simply holds 16 number

相关标签:
5条回答
  • 2020-11-30 05:06

    Loop with %c to read the stream character by character instead of %d.

    0 讨论(0)
  • 2020-11-30 05:08

    change to

    fscanf(myFile, "%1d", &numberArray[i]);
    
    0 讨论(0)
  • 2020-11-30 05:09

    5623125698541159 is treated as a single number (out of range of int on most architecture). You need to write numbers in your file as

    5 6 2 3 1 2 5  6 9 8 5 4 1 1 5 9  
    

    for 16 numbers.

    If your file has input

    5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9 
    

    then change %d specifier in your fscanf to %d,.

      fscanf(myFile, "%d,", &numberArray[i] );  
    

    Here is your full code after few modifications:

    #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;
    }
    
    0 讨论(0)
  • 2020-11-30 05:20

    There are two problems in your code:

    • the return value of scanf must be checked
    • the %d conversion does not take overflows into account (blindly applying *10 + newdigit for each consecutive numeric character)

    The first value you got (-104204697) is equals to 5623125698541159 modulo 2^32; it is thus the result of an overflow (if int where 64 bits wide, no overflow would happen). The next values are uninitialized (garbage from the stack) and thus unpredictable.

    The code you need could be (similar to the answer of BLUEPIXY above, with the illustration how to check the return value of scanf, the number of items successfully matched):

    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
        int i, j;
        short unsigned digitArray[16];
        i = 0;
        while (
            i != sizeof(digitArray) / sizeof(digitArray[0])
         && 1 == scanf("%1hu", digitArray + i)
        ) {
            i++;
        }
        for (j = 0; j != i; j++) {
            printf("%hu\n", digitArray[j]);
        }
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-30 05:23
    for (i = 0; i < 16; i++)
    {
        fscanf(myFile, "%d", &numberArray[i]);
    }
    

    This is attempting to read the whole string, "5623125698541159" into &numArray[0]. You need spaces between the numbers:

    5 6 2 3 ...
    
    0 讨论(0)
提交回复
热议问题