I"m make the efforts to read numbers from a text paper into an array. The message file, "somenumbers.txt" just holds 16 numbers as so "5623125698541159".

#include main(){ file *myFile; myFile = fopen("somenumbers.txt", "r"); //read file into variety int numberArray<16>; int i; for (i = 0; i The program 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 reverted 20 (0x14) execution time : 0.118 sPress any an essential to continue.

You are watching: Read numbers from file c++




5623125698541159 is treated as a single number (out of range of int on many architecture). You have to write numbers in your paper 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 input

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

fscanf(myFile, "%d,", &numberArray ); below is your complete code after few modifications:

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


for (i = 0; i This is attempting to check out the entirety string, "5623125698541159" into &numArray<0>. You require spaces in between the numbers:

5 6 2 3 ...


See more: The Eden Project - Times Like These, Times Like These

There room two problems in her code:

the return worth of scanf must it is in checkedthe %d counter does no take overflows right into account (blindly applying *10 + newdigit for each continuous numeric character)

The very first value you gained (-104204697) is equates to to 5623125698541159 modulo 2^32; the is thus the an outcome of an overflow (if int wherein 64 bits wide, no overflow would happen). The following values room uninitialized (garbage from the stack) and thus unpredictable.

The password you need can be (similar come the price of BLUEPIXY above, through the illustration just how to inspect the return value of scanf, the number of items effectively matched):

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