Search code examples
c++stringstream

How to ask stringstream don't split data in quotes (C++)


I'm using std::stringstream to parse some data from std::string value.
This code:

std::string str = "data1 data2 data3 \"quotated data\"";
std::stringstream ss(str);

If I use ss >> anotherStr; I get each word separated by a space.
I don't understand is there an option to ask stringstream to read data in quotes as single string value?


Solution

  • The std::quoted io manipulator is exactly what you need.

    A handy reference here: http://en.cppreference.com/w/cpp/io/manip/quoted

    and a working example:

    #include <iostream>
    #include <sstream>
    #include <iomanip>
    
    
    int main()
    {
        using namespace std;
        std::string str = "data1 data2 data3 \"quotated data\"";
        std::stringstream ss(str);
    
        std::string s;
        while (ss >> std::quoted(s))
        {
            std::cout << s << std::endl;
        }
    
        return 0;
    }
    

    expected output:

    data1
    data2
    data3
    quotated data