整数值问题
Possible Duplicate:
How can I pad an int with leading zeros when using cout << operator?
How could I show 01 in an integer?
whenever I convert a string to integer, I always get 1 instead of 01.
How could get a 01 value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
由于您将其标记为 C++,因此使用 C++ 流执行此操作的方法可能如下:
Since you tagged it as C++, the way to do it with C++'s streams could be the following:
不要将存储的值与您希望呈现的方式混淆。
您可以只使用:,
如以下完整程序所示:
输出:
Don't confuse the value that's stored with the way you want it presented.
You can just use:
as shown in the following complete program:
which outputs:
integer
类型使用其所有内存(通常为 32 或 64 位)来覆盖最大可能范围的不同整数值。它不跟踪任何格式/显示信息。因此,即使是 32 位值也可以跟踪大约 40 亿个不同的值,但是它们如何显示在屏幕上、文件中等必须由周围的代码决定,并且不是整数
本身。因此,如果您有一个整数,则可以在显示它时选择格式。有多种方法可以做到这一点。最 C++ 的方式是使用std::ostream
和
标头,其中包括对指定字段宽度和填充/填充字符的支持。有关示例,请参阅 http://www.cplusplus.com/reference/iostream/manipulators /setw/,您可以点击“另请参阅”链接来 setfill。从C继承的方式是......其中第一个双引号字符串部分包含一个“格式字符串”,其中%引入转换,0表示填充,2是宽度,d表示下一个小数/参数列表中的整数值。
The
integer
type uses all its memory - typically 32 or 64 bits - to cover the largest possible range of distinct integer values it can. It doesn't keep track of any formatting/display information. Consequently, even a 32-bit value can track some 4 billion distinct values, but however they're to be shown on-screen, in files etc. has to be decided by the surrounding code, and is not a property of theinteger
itself. So, if you have an integer, you can choose the formatting when you display it. There are a variety of ways to do this. The most C++ way is usingstd::ostream
and the<iomanip>
header, which includes support for specifying a field width and fill/padding character. For an example, see http://www.cplusplus.com/reference/iostream/manipulators/setw/ and you can follow the "See also" link to setfill. The way inherited from C is......where the first double-quoted string section contains a "format string", in which % introduces a conversion, 0 means to pad and 2 is the width, d means the next decimal/integer value in the list of arguments.
如果您使用 printf,请使用以下格式说明符
这里,百分比后面的 0 表示前导零填充,2 表示字段宽度为 2。
If you are using printf, use the following formate specifier
Here, the 0 after percentage indicates leading zero padding and 2 indicates a field width of 2.
作为整数,它始终为 1,
仅当您将 01 转回字符串以进行显示时,才能显示它。
最好的方法是使用 printf
As an integer, it will always be 1,
You can only display 01 when you turn it back into a String for display purposes.
The best way would be to use the printf
使用格式化程序显示值时,您可以编写:
请参阅 C++ 参考文档: http:// /www.cplusplus.com/reference/clibrary/cstdio/printf/
When displaying the value using a formatter you can write:
See the C++ reference documentation: http://www.cplusplus.com/reference/clibrary/cstdio/printf/