Reading numbers from a text file into an array in C

后端 未结 5 708
囚心锁ツ
囚心锁ツ 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: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 
    
    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;
    }
    

提交回复
热议问题