Вопрос:

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

c++ arrays fstream

4440 просмотра

1 ответ

35 Репутация автора

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?

Автор: Preston White Источник Размещён: 09.11.2017 12:02

Ответы (1)


2 плюса

31 Репутация автора

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..

Автор: user8515431 Размещён: 09.11.2017 12:14
Вопросы из категории :
32x32