Reputation: 2077
Now this is a little confusing for me, but std::string::iterator actually yields a char (as revealed by typeid). I need it as a string though. How can I do this?
#include <string>
#include <iterator>
int main(){
std::string str = "Hello World!";
for( std::string::iterator it = str.begin(); it != str.end(); it++ ){
std::string expectsString(*it); // error
std::string expectsString(""+*it); // not expected result
myFunction(expectsString);
}
}
I'm using gcc 5.4.0 with C++11 enabled.
edit: As this needs further clarification I want to convert *it to a string. So I can use the currently iterated through character as a string, instead of a char. As my failed examples in the above code example demonstrate, I was looking for something like
std::string myStr = *it; //error
Upvotes: 2
Views: 15767
Reputation: 5181
You can declare the string and later can use that for storing *it to that string and can use, which you can use as string anywhere.
std::string el;
list <std::string> :: iterator it;
for(it = variableOrder.begin(); it != variableOrder.end(); it++){
el = *it;
cout << el << endl;
}
Upvotes: 0
Reputation: 217115
Another alternatives:
std::string expectsString{*it}; // Use initializer_list<char>
std::string expectsString({*it}); // Use initializer_list<char>
Upvotes: 1
Reputation: 6240
Could also construct string of length 1 from it
using range constructor
std::string expectsString(it, it+1);
Upvotes: 3
Reputation: 310930
Use instead
std::string expectsString(1, *it);
Here is a demonstrative program
#include <iostream>
#include <string>
int main()
{
std::string str = "Hello World!";
for( std::string::iterator it = str.begin(); it != str.end(); it++ )
{
std::string expectsString( 1, *it );
std::cout << expectsString;
}
std::cout << std::endl;
return 0;
}
Its output is
Hello World!
Upvotes: 4