似乎 sprintf 和 Boost.Format 都使用空格来填充:
boost::format fmt("%012s");
fmt % "123";
std::string s3 = fmt.str();
有没有办法用'\0'填充?
最佳答案
问题被标记为 c++ .虽然,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
由于 '\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
关于c++ - 字符串格式用\0填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51687129/