Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string::iterator to std::string

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
like image 862
infinitezero Avatar asked May 22 '26 10:05

infinitezero


1 Answers

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!
like image 118
Vlad from Moscow Avatar answered May 25 '26 00:05

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!