Search code examples
c++stringconstructortype-conversionstringstream

Conversion to string if input may be a string with spaces and line breaks


I am trying to convert any input of arithmetic type or char or string (including spaces and or line breaks) to a string.

I tried using to_string which works for any input but string.

I then tried

void dataToString() {
    std::stringstream ss;
    ss << cryptedData;
    ss >> dataString;
}

which works even for strings as an input but will only take the string up to the first space. How can this be altered to store the entire string but also work for any input type mentioned above.

Note that I can not use conditionals to run different code for different types as this is done in the constructor of a class so it wont compile if any of the possible inputs is run through any of the loops.


Solution

  • To get the contents of a stream as string, you can simply use the str member function:

    std::string dataToString()
    {
        std::ostringstream ss;
        ss << cryptedData;
        dataString = std::move(ss).str();
    }