c++ - 字符串格式用\0填充?

标签 c++ boost

似乎 sprintf 和 Boost.Format 都使用空格来填充:

boost::format fmt("%012s");
fmt % "123";
std::string s3 = fmt.str();

有没有办法用'\0'填充?

最佳答案

问题被标记为 .虽然,OP 提到了 sprintf 和 Boost.Format 但没有提到 C++ 的输出流运算符。这让我有点惊讶。

虽然我怀疑这在 OP 的网络协议(protocol)中是否真的需要/需要——使用 C++ 输出运算符和 iomanip 它变得相当容易。

示例代码:

#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
  std::ostringstream out;
  out << std::setw(10) << std::setfill('\0') << 123;
  const std::string dump = out.str();
  std::cout << "length of dump: " << dump.size() << '\n';
  for (char c : dump) {
    std::cout << ' ' << std::setw(2) << std::setfill('0')
      << std::setbase(16) << (unsigned)(unsigned char)c;
  }
  // done
  return 0;
}

输出:

length of dump: 10
 00 00 00 00 00 00 00 31 32 33

Live Demo on coliru

由于 '\0' 是不可打印的字符,我将输出输出到 std::ostringstream 中,检索输出为 std::string 并将单个字符打印为十六进制代码:

  • std::setw(10) 导致右对齐到 10 个字符。
  • std::setfill('\0')'\0' 字节填充。
  • 31 32 33123 为输出指定的 int 常量的 ASCII 代码。

我错过了 OP 想要格式化字符串(而不是数字)的事实。但是,它也适用于字符串:

格式:

out << std::setw(10) << std::setfill('\0') << "abc";

输出:

length of dump: 10
 00 00 00 00 00 00 00 61 62 63

Live Demo on coliru

关于c++ - 字符串格式用\0填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51687129/

相关文章:

c++ - 在 Winx64 中使用 Boost::asio:我卡住了,需要弄清楚如何为 x64 构建 libboost_system_xxxx.lib

c++ - 如何插入到 Boost MPL 映射中

c++ - 创建boost::shared_ptr的深层拷贝

c++ - 使用 dynamic_cast 的奇怪行为

c++ - 管理多个并发线程

c++ - 使用Cmake输出库信息

c++ - nvcc 和 BOOST 库的编译错误

c++ - 我应该丢弃 boost::python::exec 的返回值吗?

c++ - 每个类重载 new(),而不是全局重载

c++ - 如何删除第一个数组的某个索引处的所有元素并且该索引取自第二个数组?