用\ 0填充字符串格式?

时间:2018-08-04 15:38:12

标签: c++ boost

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

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

是否可以使用'\ 0'填充?

1 个答案:

答案 0 :(得分: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 33是为输出指定的123常量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