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

冷暖自知 提交于 2019-12-13 03:08:20

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/47191810/read-from-a-text-file-and-storing-to-an-array-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!