【问题标题】:How to save hex representation of binary file into a std::string?如何将二进制文件的十六进制表示保存到 std::string 中?
【发布时间】:2016-01-04 15:54:24
【问题描述】:

我已经使用了这个解决方案(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::cout &lt;&lt; buffer.str();?
  • 与你的问题无关,但在几乎所有情况下(包括这个),while (!fin.feof()) 都不会像你期望的那样工作。而是做while (fin &gt;&gt; x)

标签: c++ string hex fstream stringstream


【解决方案1】:

您没有std::string;你有一个std::stringstream。而且您不能“打印”字符串流,但您可以使用str() 成员函数获取其缓冲区的std::string 表示形式。

你的意思可能是:

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

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

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

【讨论】:

  • 当然...感谢您的帮助。那行得通。过早检查 EOF 是什么意思?也会改变do, while 循环帮助吗?
  • @Patryk:实际上可能。
猜你喜欢
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
  • 2023-04-03
  • 2022-06-22
  • 2011-08-24
  • 2014-10-30
  • 2012-04-08
  • 2013-02-21
相关资源
最近更新 更多