简体   繁体   中英

conversion to string with std::stringstream fails on white spaces

I am trying to convert any string or character or number to std::string with std::stringstream . This is what I am doing:

template<typename T>
std::string toString(T a){
    std::string s;
    std::stringstream ss;
    ss <<a;
    ss >>s;
    return s;
    }

int main(int argc, char* argv[]) {
    char s[100]="I am a string with spaces";
    std::cout<<toString(s);

    return 0;
} 

But it fails on the first white space.

Output:

I

Expected Ouput:

I am a string with spaces

How can I do this.

Note: s can contain newline character too.

You can directly access the stringified content of a stream with the std::ostringstream::str() member function.

template <typename T>
std::string toString(const T& a)
{
    std::ostringstream ss;
    //   ↑
    ss << a;
    return ss.str();
    //     ~~~~~~~^
}

DEMO

operator<< has no problem inserting s into the stringstream. It's no different than if you did std::cout << s . What you're doing wrong is extracting from the stream into s . This will only read up to a whitespace character (which includes both spaces and newlines.) To get the contents of the stream, do:

return ss.str();

This however is just a convoluted way of doing:

std::string str = s;

Just reduce your entire program by 10 lines:

#include <iostream>

int main(int argc, char* argv[]) {
    char s[100]="I am a string with spaces";
    std::cout<<std::string(s);

    return 0;
} 

If you really need to use stringstream, then there is one of possible solutions: (I do not pretend to have a good code)

template<typename T>
std::string toString(T a) {
    std::stringstream ss;
    ss << a;
    const char* s = ss.str().c_str();
    ss.read((char *)s, ss.str().length());
    return s;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM