似乎sprintf和Boost.Format都使用空格填充:
boost::format fmt("%012s");
fmt % "123";
std::string s3 = fmt.str();
是否可以使用'\ 0'填充?
答案 0 :(得分:3)
该问题被标记为c++。虽然,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
由于'\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