c++asciiistringstream

Using an istringstream With ASCII 26 Character


I have a fairly simple ask, but I haven't been able to find any help anywhere, so I was hoping for some help. I'm working with some C++ stringstreams and I have string data that is causing my stream to fail. Specifically, the stream fails when I encounter the Ctrl-Z character (26 or 0x1A), which isn't particularly surprising.

To start with, I have a string of data that represents an image, in the sense that each byte (or character) of the string represents some RGB value of an image somewhere (the exact image structure does not matter). From this string, I want to reconstruct the image of RGB values that it represents. The approach that I took was to transform the string into a stringstream so I could better parse the data, since the beginning bytes contain header information that I need.

It sort of looks like this:

std::string data = getImageData(); // Get the image from somewhere
std::istringstream ss(data);
char byte = ' ';
while (ss.get(byte)) {
   // PROCESS THE BYTE
}

This works just fine until it inevitably reaches some byte with ASCII value 26, which ordinarily is an EOF marker, and the stream throws up its flags and marks it as a failure. Once this happens, the stream terminates and I can no longer read data from the stream. I was wondering how I could bypass this error and keep reading until the stream is empty.

What I Have Done/Researched

The string data is beyond my control. I cannot change what it is, but I could theoretically change values of it once I have retrieved it, since it is a copy of the original image data. In general, it is supposed to be image data in a particular format, so beyond its header the byte values could be anything, even ASCII 26.

Many suggestions that I have seen say to open the stream with std::ios::binary, but this doesn't work either. Further research suggests that this mode does not exist for stringstreams, but does exist for file streams. Theoretically, if the data came from a filestream instead of a stringstream then there wouldn't be an issue. Unfortunately, again, the data must come in as a string, so this is beyond my control. From there, I am just ignorant if there is a way to read a stringstream as true binary and I just can't figure it out.

The big question is this: is there a way to read individual bytes from a stringstream in binary mode such that ASCII character 26 does not cause an issue, or is there a better way to manage the string data in the first place as it comes in so that this is not an issue?

Thank you for reading!


Solution

  • I suggest avoiding use of std::istringstream altogether. Since you seem to be working with one character at a time, just iterate over the string and process each character as you see fit.

    std::string data = getImageData();
    for (char ch : data)
    {
       // Use ch
    }