Reputation:
I want to iterate through a string vector in c++. I want to open each item in the list with fopen.
const char *filep //fopen needs a constant char pointer.
for (vector<string>::iterator it = filelist.begin(); it != filelist.end(); it++)
{
filep = (const char *)it; //This isn't working. How can I fix this
fopen(filep, "rb");
}
Upvotes: 2
Views: 716
Reputation: 234665
You should have used it->c_str()
as it
is essentially a pointer to the element in the std::vector
. But for an easier life use
for (const auto& s : filelist){
// s is a const reference to an element in filelist
// use s.c_str() if you need the character buffer
}
This is valid from C++11 onwards. Using const auto&
rather than auto
obviates a std::string
copy.
Upvotes: 6
Reputation: 73366
Change this:
filep = (const char *)it;
to this:
filep = it->c_str();
However, you do extra, unnecessary steps, since you could just do this instead:
for (vector<string>::iterator it = filelist.begin(); it != filelist.end(); it++)
fopen(it->c_str(), "rb");
which reduces the number of lines of your code to just two, and doesn't use an extra pointer.
PS: A more modern approach can be found in Bathsheba's answer, or use the auto&&
approach.
Upvotes: 2
Reputation: 605
A std::string
is a type which is completely different from const char *
. Hence, you need to get underlying character buffer
stored in string. For that You must use method std::string::c_str()
or std::string::data()
whatever you like.
Do it like below (Inspired from other answers now using range-based for-loop
),
const char *filep //fopen needs a constant char pointer.
for (auto & str : filelist)
{
filep = str.c_str();
fopen(filep, "rb");
}
Upvotes: 0
Reputation: 76
create a method getstring in which you will return the string.
for(unsigned int i=0; i<iterator.size();i++){
cout << iterator[i]->getstring()<<endl;
}
Upvotes: 0