Reputation: 97
I'm working on a function that reads a file, stores every line whose starting with a colon, and removes every dash contained in the string.
Every time this kind of line is found, push_back() is used to store it in a vector.
The problem is that, every time push_back() is used, all the elements in the vector take the value of the last one. I don't understand why it happens. Here's the code :
string listContent;
size_t dashPos;
vector<char*>cTagsList;
while(!SFHlist.eof())
{
getline(SFHlist, listContent);
if(listContent[0] == ':')
{
listContent.erase(0, 1);
dashPos = listContent.rfind("-", string::npos);
while(dashPos != string::npos)
{
listContent.pop_back();
dashPos = listContent.rfind("-", string::npos);
}
char* c_listContent = (char*)listContent.c_str();
cTagsList.push_back(c_listContent);
}
}
I first thought it was a problem with the end of the file but aborting the searching process before reaching this point gives the same results.
Upvotes: 0
Views: 131
Reputation: 565
the c_str()-method of std::string states:
The pointer returned may be invalidated by further calls to other member functions that modify the object.
If you're allowed to use a std::vector< std::string > instead of the vector of char*, you're fine since there would be always a copy of the std::string listContent pushed into the vector, ie.
std::string listContent;
size_t dashPos;
std::vector<std::string>cTagsList;
while(!SFHlist.eof())
{
getline(SFHlist,listContent);
if(listContent[0]==':')
{
listContent.erase(0,1);
dashPos = listContent.rfind("-",string::npos);
while(dashPos!=string::npos)
{
listContent.pop_back();
dashPos = listContent.rfind("-",string::npos);
}
cTagsList.push_back(listContent);
}
}
(I haven't tested it)
Upvotes: 2