我有一个接受一些整数参数的函数,然后需要将其转换为固定长度为 4 的 ASCII 字符串表示形式。即 4 变为“0004”,42 变为“0042”。假设参数为 0<=n<=9999
是安全的我可以用类似的东西来做到这一点:
void foo(int a, int b) {
std::string sa = std::to_string(a);
std::string sb = std::to_string(b);
for(int i = sa.length; i < 4; i++)
sa.insert(0,"0");
...
}
但这似乎超出了我的需要,尤其是在有很多参数要转换的情况下。有没有更有效的方法来做到这一点?
编辑:目标不是打印结果字符串。
编辑 2:基于 ss << std::setw( 4 ) << std::setfill( '0' ) << number;
的东西做我需要的,谢谢你的评论。
最佳答案
您可以使用 std::ostringstream
并将其视为输出流:
std::ostringstream ss;
ss << std::setw( 4 ) << std::setfill( '0' ) << number;
Send_To_Serial(ss.str().c_str());
关于c++ - int 到固定长度的字符串表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24617876/