字符串格式填充\ 0?

问题描述 投票:1回答:1

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

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

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

c++ boost
1个回答
3
投票

这个问题被标记为。虽然,OP提到了sprintf和Boost.Format,但没有提到C ++的输出流操作符。这对我来说有点令人惊讶。

虽然我怀疑OP的网络协议是否真的需要/需要 - 使用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的ASCII码,int常数用于输出。

我错过了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

© www.soinside.com 2019 - 2024. All rights reserved.