There is a hexstr_to_str function that reads from memory (not a file, not cin) a text stream of the form "01 03 10 fa", and writing to std :: string containing \ x01 \ x03 \ x10 \ xfa. The problem with reading integers from a stream is that after reading the last number , the flag is set in the failbit stream. Is there an alternative to istringstream, or after reading each number from the stream, it is necessary to do a check at the end of the string, for example, through peek ()? Is there a simpler solution?
#include <iostream> #include <sstream> ssize_t hexstr_to_str(std::string &destination, std::istringstream &stream_source) { std::ios::fmtflags old_flags = stream_source.setf(std::ios::hex, std::ios::basefield); size_t count = 0; int symbol = -1; destination.clear(); while ( stream_source >> symbol ) //добавление && !stream_source.eof() результата не дало. { destination += symbol; ++count; } stream_source.setf(old_flags); std::cout << (stream_source.rdstate() & (stream_source.failbit | stream_source.badbit))<<"\n"; return !(stream_source.rdstate() & (stream_source.failbit | stream_source.badbit)) ? count : -count; } int main() { std::string hb_str; //std::cout << hexstr_to_str(hello_str, std::istringstream(cstr_hex_hello)); hexstr_to_str(hb_str, std::istringstream("10 20 af 30")); return 0; }