Will Gwo Will Gwo - 3 months ago 10
C++ Question

Read ints recusively from file into array, the second last element always wrong

#include <iostream>
#include <fstream>
using namespace std;

int fillArray(ifstream& ifs, int array[]){
int cur;
int counter = 0;

if(ifs>>cur){
counter = fillArray(ifs, array) + 1;
array[counter-1] = cur;
}

return counter;
}



int main(int argc, const char * argv[]) {

int count;
int array[] = {0};
ifstream myfile ("/Users/Desktop/example.txt");


count = fillArray(myfile, array);

for (int i = 0; i<count; i++){
cout<<array[i]<<endl;
}

myfile.close();

return 0;
}


For example, if the input file is "1 2 3 100 19 16 33", the resulted array is "33 7 19 100 3 2 1".
if the input file is"1 2 3 4 5", the array will be "5 5 3 2 1".
I don't mind ints are filled in reversely, but I don't understand what happened to the second last ints.

And this code works fine in VS, it only has problem in xcode.

Answer

This code only "works fine in VS" by accident. It creates an array with one element, then stores past the end of the array, so it's deep into undefined behavior. Instead of a hard-coded array, use std::vector<int>; that will let you add as many elements as are needed. Each time you get a new element you can call push_back to put it into the vector.

Comments