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 numbers as so "5623125698541159".
#include <stdio.h> main() { FILE *myFile; myFile = fopen("somenumbers.txt", "r"); //read file into array int numberArray[16]; int i; 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]); } }
The program doesn't work. It compiles but 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 s Press any key to continue.
Use fstream to Read Text File Into 2-D Array in C++ To read our input text file into a 2-D array in C++, we will use the ifstream function. It will help us read the individual data using the extraction operator. Include the #include<fstream> standard library before using ifstream .
change to
fscanf(myFile, "%1d", &numberArray[i]);
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With