C++中ToString("00.00000")的等价物是什么?
what is the equivalent of ToString("00.00000") in C++?
我尝试了以下操作来获取.ToString("00.00000"),但失败
char buf[500];
memset(buf, 0, sizeof(buf));
sprintf_s(buf, "%02.7f",abc);
std::string abc_str = buf;
我意识到%02没有任何影响,例如,当我得到7.0时,结果是7.0000000,而不是期望的07.0000000,这里有什么错吗?
谢谢!
C++中的等价物是:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setw(10) << std::setfill('0')
<< std::fixed << std::setprecision(7) << 7.0;
return 0;
}
输出:
07.0000000
如果您需要将其实际存储到std::string
中,则:
#include <sstream>
std::ostringstream oss;
// ...
std::string s = oss.str();
代码:
#include <stdio.h>
int main() {
char buf[500];
printf("%010.7fn", 7.0);
}
输出:
07.0000000
评论
请注意,10是整个字段的最小宽度,而不仅仅是小数的左手边。