简体   繁体   中英

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, ie

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM