如何将二进制文件的十六进制表示形式保存到 std::string?

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

我已经使用了这个解决方案 (c++) Read .dat file as hex using ifstream 但我不想将它打印到 std::cout 我想将二进制文件的十六进制表示形式保存到 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;
}

打印到 cout 有效,但将这些内容保存到 buffer 然后尝试将其打印到 cout 打印垃圾。

我错过了什么?

您没有 std::string;你有一个 std::stringstream。你不能 "print" 一个字符串流,但你可以使用 str() 成员函数获得其缓冲区的 std::string 表示。

那么你的意思可能是:

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

有更简洁的方法可以做到这一点,但以上内容可以帮助您入门。

顺便说一句,你的循环是错误的。您检查 EOF 的时间太早了。