c++while-loopifstreamgetc

Reading file of character data with while loop


I have a file with data like:

1F B8 08 08 00 00 00 00

I am reading it into an int, casting it to a character, and storing it in an array.

int n, i = 0;
char c;
while (ifs >> std::hex >> n) {
   c = static_cast<unsigned char>(n);
   r[i++] = c;
}

works fine. How do I go about doing this if there is no white space in the data, i.e.

1FB8080800000000

The above code just fills n to maxint and exits. I can create something using getc or the like but I'd like the C++ code to handle both cases.


Solution

  • You could read the numbers as strings and use std::setw to limit the number of characters read. Then use std::stoi to convert to integers:

    std::string ns;
    while (ifs >> std::setw(2) >> ns) {
        r[i++] = static_cast<unsigned char>(std::stoi(ns, nullptr, 16));
    }
    

    Will work with both the space-delimited and non space-delimited input.