Search code examples
c++winapifstream

How to store strings while retaining the ability to extract formatted string(like cout)?


I'm currently working on a static library that works on both Windows8 and Win32 and I hit the problem where I'd like to load text files. Gathering the raw data was the easy step, the only problem is that I'd also like to retain some of fstreams capabilites, more exactly the extraction operator (>>) because there is a lot of parsing code that uses that operator. Is there an easy way of doing it, using some of the standard library code maybe?


Solution

  • You can initialise a std::stringstream with your std::string:

    std::string str = "string I want to parse";
    std::stringstream ss(str);
    

    This type is derived from std::basic_iostream, so you can can use the same extraction and insertion operators on it as you please. For example:

    std::string word;
    ss >> word; // Extracts the word "string"
    

    If you only want to extract from it, try a std::istringstream.