My Code is reading a set of Elements from a file and adds those to a Vector. The for-loop reads all the elements and via push_back they are added to the vector. Works perfectly fine on paper BUT: In the end all the Elements in the Vector are equal and always the last read element.

I am 100 percent certain the Elements listed in the File aren't the same (because of the good old NotePad++). Ive tried to c-out the read in elements to check if there is a problem with the f_read function. The Program outputted the Elements perfectly fine and in the right order. I am guessing the error isn't with the file or the f_read function.

FILE* f = fopen(filepath, "rb");unsigned char header[19];fread_s(header, sizeof(header), sizeof(unsigned char), 19, f);vector<char*> myVector;int size = 28 * 28;char temp[28 * 28];for (int i = 0; i < 2; i++) {fread_s(temp, 28*28, sizeof(unsigned char), size, f);myVector.push_back(temp);}

( the 19 bits i am reading into the "info" char array are the header)

I Expect the Vector to contain all the Read Elements in the right order.

1

Best Answer


As mentioned in the comments, you are pushing the pointers back not the actual strings. To get the actual strings you can do this:

void readFileToVec(){ifstream file;file.open ("rb");vector<string> v;string word;while (file >> word){v.push_back(word);}}

This will work if the elements are all strings and are seperated by a space,tab, or newline. If your words are seperated by anything other than one of these three (for example a list of words separated by commas) then you can use getline and specify the separator.

In any case, reading about C++ streams and the difference between C-style strings and STL strings would be worthwhile if you intend to do this sort of thing with C++ again. You are using C Strings and old school FILE which is part of the C Library while C++ provides you with utilities to make your life easier. File streams and C++ strings are great examples of such utilities.