[英]Printing integers with a fixed number of zeros in C++
The question is simple.问题很简单。 I have messed up with std::fixed , std::setprecicion , std::setw , but none of them solves my problem.
我搞砸了std::fixed 、 std::setprecicion 、 std::setw ,但它们都没有解决我的问题。
If I have a integer variable equal to 1, I want it to be printed as: 1000如果我有一个 integer 变量等于 1,我希望它打印为: 1000
Thank you.谢谢你。
I think you mean you want it to print as 0001, not as 1000.我想你的意思是你希望它打印为 0001,而不是 1000。
Look at printf / sprintf with a format string.查看带有格式字符串的 printf / sprintf。 For example:
例如:
#include <iostream>
int main(int argc, char **argv) {
int i = 1;
printf("%04d\n", i);
}
The question is not very clear on what you are trying to achieve.关于您要达到的目标,这个问题不是很清楚。
If you want to print the value of your variable with 3 zeroes appended to it, you should just print the variable and then 3 zeroes.如果要打印附加了 3 个零的变量的值,则应该只打印变量,然后打印 3 个零。
cout << x << "000" << endl;
If you need to do any computation with it, you could always just multiply it by 1000
.如果你需要用它做任何计算,你总是可以把它乘以
1000
。
int y = x * 1000;
cout << y << endl;
Keep in mind that this may cause an overflow, though...请记住,这可能会导致溢出,但是...
You can use std::left
together with std::setw
and std::setfill
to add a number of specific fill characters on the right.您可以将
std::left
与std::setw
和std::setfill
一起使用以在右侧添加许多特定的填充字符。 Example with std::cout
: std::cout
示例:
#include <iostream>
#include <iomanip>
#include <ios>
int main() {
std::cout << std::setw(4) << std::setfill('0') << std::left << 1;
return 0;
}
I believe it should do the job.我相信它应该完成这项工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.