0

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?

Community
  • 1
  • 1
Patryk
  • 22,602
  • 44
  • 128
  • 244

1 Answers1

4

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055