I'm trying to read a list of arrays from an input file, do something with it, then print the results. I noticed that I was incorrectly reading the arrays, but I couldn't figure out what I was doing wrong. The problem appears to be that random numbers from previous arrays get added to the end of the subsequent arrays.
To test my code, I added a few lines to make it print out the original arrays that the code read, and it clearly shows that the arrays are no longer the same. I included an example of the original array and my output at the end.
Any help would be greatly appreciated!
This is the part in my code that reads the arrays from the input file:
int a[50]={0};
ifstream inputFile;
string s;
stringstream ss;
string outputfile = "out.txt";
...
int n;
char c;
inputFile.open("in.txt");
while(getline(inputFile, line)){
int stringSize = line.length();
line = line.substr(1, stringSize - 2);
istringstream input(line);
string number;
vector<int> ints;
while(getline(input, number, ',')){
istringstream iss(number);
int i;
iss >> i;
ints.push_back(i);
}
copy(ints.begin(), ints.end(), array);
int size = sizeof(array) / sizeof(array[0]);
a1(array, size, outputfile);
}
inputFile.close();
a1() is the function where I do things with the arrays I read, but that's also where I included the print function for testing.
This is the print part:
ofstream output;
output.open(filename.c_str(), ios::out | ios::app);
output << "Original array: ";
for (int x = 0; x < size; x++) {
output << a[x];
if (x != size-1) output << ", ";
}
This is what the in.txt looks like:
[1, 2, 4, -1, 4, -10, 4, -19, 18, -1, -3, -4, 11, 3, -20, 19, -33, 50, 66, -22, -4, -55, 91, 100, -102, 9, 10, 19, -10, 10, 11, 11, -10, -18, 50, 90]
[12, 12, 14, -88, -1, 45, 6, 8, -33, 2, 8, -9, -33, -8, -23, -77, -89, 1, 9, 10, 92, 87]
[565, 78, 33, 9, 10, 84, 71, -4, -22, -55, -10, 76, -9, -9, -11, 76, 89, 11, 10, -33, 9]
[2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
[2]
[-1, -1, -1, -1, -1, -100, -10, -10, 100, 100, 100, 100, -100, 100, 10, -10, -1]
[12, 23, 44, -17, 12, 14, -88, -1, 45, 6, 8, -33, 2, 8, -9, -33, -8, -23, -77, -89, 1, 9, 13, -25, 10, 92, 57, 99, -22]
This is what my out.txt looks like right now:
1, 2, 4, -1, 4, -10, 4, -19, 18, -1, -3, -4, 11, 3, -20, 19, -33, 50, 66, -22, -4, -55, 91, 100, -102, 9, 10, 19, -10, 10, 11, 11, -10, -18, 50, 90, 0
12, 12, 14, -88, -1, 45, 6, 8, -33, 2, 8, -9, -33, -8, -23, -77, -89, 1, 9, 10, 92, 87, 91
565, 78, 33, 9, 10, 84, 71, -4, -22, -55, -10, 76, -9, -9, -11, 76, 89, 11, 10, -33, 9, 87
2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 11
2, 3
-1, -1, -1, -1, -1, -100, -10, -10, 100, 100, 100, 100, -100, 100, 10, -10, -1, 3
12, 23, 44, -17, 12, 14, -88, -1, 45, 6, 8, -33, 2, 8, -9, -33, -8, -23, -77, -89, 1, 9, 13, -25, 10, 92, 57, 99, -22