I"m trying to review numbers from a text document into one array. The message file, "somenumbers.txt" just holds 16 numbers as so "5623125698541159".

#include main(){ paper *myFile; myFile = fopen("somenumbers.txt", "r"); //read file into selection int numberArray<16>; int i; because that (i = 0; ns The regimen doesn"t work. The compiles yet outputs:

Number is: -104204697

Number is: 0

Number is: 4200704

Number is: 2686672

Number is: 2686728

Number is: 2686916

Number is: 2004716757

Number is: 1321049414

Number is: -2

Number is: 2004619618

Number is: 2004966340

Number is: 4200704

Number is: 2686868

Number is: 4200798

Number is: 4200704

Number is: 8727656

Process returned 20 (0x14) execution time : 0.118 sPress any an essential to continue.

You are watching: Read integers from file c++ into array




5623125698541159 is treated as a solitary number (out of variety of int on most architecture). You need to write numbers in your document as

5 6 2 3 1 2 5 6 9 8 5 4 1 1 5 9 because that 16 numbers.

If your file has intake

5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9 then adjust %d identify in her fscanf to %d,.

fscanf(myFile, "%d,", &numberArray ); here is your full code after couple of modifications:

#include #include int main(){ paper *myFile; myFile = fopen("somenumbers.txt", "r"); //read document into selection int numberArray<16>; int i; if (myFile == NULL) printf("Error reading File\n"); leave (0); because that (i = 0; i


for (i = 0; ns This is attempting to review the whole string, "5623125698541159" into &numArray<0>. You need spaces between the numbers:

5 6 2 3 ...


See more: Solved Which Of The Following Is A Direct Cost Of Manufacturing A Sport Boat?

There are two difficulties in her code:

the return worth of scanf must be checkedthe %d conversion does no take overflows right into account (blindly applying *10 + newdigit because that each continually numeric character)

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

The code you need could be (similar come the prize of BLUEPIXY above, v the illustration exactly how to examine the return value of scanf, the variety of items efficiently matched):

#include int main(int argc, char *argv<>) int i, j; brief unsigned digitArray<16>; i = 0; while ( ns != sizeof(digitArray) / sizeof(digitArray<0>) && 1 == scanf("%1hu", digitArray + i) ) i++; because that (j = 0; j != i; j++) printf("%hu\n", digitArray); return 0;