Preston White
Preston White

Reputation: 97

Read from a text file and storing to an array C++

I have a program that reads values from a text file(sortarraysin.txt) and stores those values into an array. However when I try to print the array to the console my output does not display the numbers from the text file. My text file and program are shown below.

Text file:

45 59 302 48 51 3 1 23

Program:

int array[8];
int i = 0;
string inFileName, getcontent;
cout << "Enter input file name -> ";
cin >> inFileName;
fstream inFileStr(inFileName.c_str(), ios::in);
if(inFileStr.fail()){
    cerr << "Unable to open " << inFileName << endl;
    exit(-1);
}
if(inFileStr.is_open()){
    while(!inFileStr.eof()){
        getline(inFileStr, getcontent);
        cout << getcontent << endl;
        array[i++] << atoi(getcontent.c_str());
        for(i=0;i<=8;i++){
        cout << array[i] << " ";
        }
    }
}

Output:

Enter input file name -> sortarraysin.txt 
45 59 302 48 51 3 1 23
-2145069216 1 -13232 0 -2145069216 1 -12816 0 -13136

Why are my array values printing these numbers instead of the values from the text file?

Upvotes: 0

Views: 19274

Answers (1)

user8515431
user8515431

Reputation: 41

int value;
int i = 0;
while(inFileStr >> value)
{ 
   myArray[i] = value;
   i++;
}

you don't need to use getline if you follow my instruction, and you will not need to convert string to integer. Remember less code is faster..

Upvotes: 2

Related Questions