0

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
  • 77
  • 1
  • 1
  • 9
  • 1
    So, why not read the numbers as numbers? Might want to read this too: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong If all your numbers are on the same line and you read the whole line you'll need to do something to split that line up before you convert it to numbers. But really, just read numbers.. – Retired Ninja Nov 09 '17 at 00:04
  • @RetiredNinja How would I go about doing this? – Preston White Nov 09 '17 at 00:09
  • 3
    `int num; while(file >> num) { do something with the number }` – Retired Ninja Nov 09 '17 at 00:10

1 Answers1

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

  • 1
    Recommend adding a `&& i < maxArraySize` to the `while` loop to prevent overrunning the end of the array if the file is larger than expected. Minor nag: "less code is faster" not always. The simpler code could induce more cache misses or have poor predictability for orders-of-magnitude slowdowns over a solution that looks more cumbersome. – user4581301 Nov 09 '17 at 00:44