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?
 
     
    