Patryk
Patryk

Reputation: 24092

How to save hex representation of binary file into a std::string?

I have used this solution (c++) Read .dat file as hex using ifstream but instead of printing it to std::cout I would like to save binary file's hex representation to a std::string

#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <iomanip>

int main(int argc, char** argv)
{
  unsigned char x; 

  std::ifstream fin(argv[1], std::ios::binary);
  std::stringstream buffer;

  fin >> std::noskipws;
  while (!fin.eof()) {
    fin >> x ; 
    buffer << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(x);
  }
  std::cout << buffer;
}

Printing to cout works but saving those contents to buffer and then trying to print it to cout prints garbage.

What am I missing?

Upvotes: 0

Views: 455

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

You don't have a std::string; you have an std::stringstream. And you can't "print" a stringstream, but you can obtain the std::string representation of its buffer, using the str() member function.

You probably meant, then:

std::cout << buffer.str();

There are cleaner ways to do this, but the above will get you started.

As an aside, your loop is wrong. You're checking for EOF too soon.

Upvotes: 4

Related Questions