Loops and vectors

This is a pretty basic issue that I am embarrassingly stumped on.

I am reading in lines in a file and pushing those lines in a vector of char array. The vectors seem to contain all the different lines when I output it within the loop, however, when I test the vector content outside the loop all the vector elements just contain the last line inserted so if I have a vector of

1,2,3

the output of vector elements outside the loop becomes

3,3,3


I haven't found this issue previously and I am unsure what would cause this problem.

this is the line.


for (int i = 0; i < 265938; i++){
dict.getline (line, 100); //ifstream dict with a file open
for (int j = 0; j < 1024; j++)
line[j] = tolower(line[j]);
dictionary.push_back(line);
}
for (int k = 0; k < 265938; k++)
cout << dictionary.at(k) << endl;
closed account (z0My6Up4)
I'm not sure about the rest but the last loop in your code looks odd. You should use the types that return iterators to traverse the vector. eg you could write something like this instead of the last for loop:
while (dictionary.begin( ) != dictionary.end( )) { // output next element }

or try if using c++11

1
2
for (auto i : dictionary)
cout << i;


This might not be the problem though.
Last edited on
You should also avoid magic numbers like "265938" and "1024." Also why are you using a vector of char arrays? Have you considered using a vector of strings? std::vector<std::string> dictionary; I would also suggest giving it an initial size or capacity since you have a decent number of elements.
Topic archived. No new replies allowed.