Integer Value Problem [duplicate]
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.
Since you tagged it as C++, the way to do it with C++'s streams could be the following:
#include <sstream>
#include <iomanip>
#include <iostream>
int main() {
int value = 1;
std::stringstream ss;
ss.width(2);
ss << std::setfill('0') << value;
std::cout << ss.str() << std::endl; // displays '01'
}
Don't confuse the value that's stored with the way you want it presented.
You can just use:
std::cout << std::setfill('0') << std::setw(2) << 1;
as shown in the following complete program:
#include <iostream>
#include <iomanip>
int main() {
int x = 1;
std::cout << std::setfill('0') << std::setw(2) << x << std::endl;
return 0;
}
which outputs:
01
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 the integer
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 using std::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...
printf("%02d", n);
...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.
If you are using printf, use the following formate specifier
printf("%02d\n",myInt);
Here, the 0 after percentage indicates leading zero padding and 2 indicates a field width of 2.
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
printf("%02d", x);
When displaying the value using a formatter you can write:
%02d
See the C++ reference documentation: http://www.cplusplus.com/reference/clibrary/cstdio/printf/
精彩评论