Basics: Is it possible to print 05 rather than 5?

int x;
cin >> x;
//If user writes 05 in x. Then I want that 05 should be printed when we cout << x;
//If user writes 005 when prompted for x then printing x should print 005, because 005 may be a telephone extension.
Is there any way?
Leading zeros are lost when you read the data in as an integer. If you want to remember them, you'll have to read the data as a string.

1
2
std::string x;
cin >> x;  // now you'll keep the 0's... but you also have a string instead of an int 


If you need an integer.... you could do some text processing on the string to see how many leading zeros there are, and track that in a separate variable.... then convert the string to an integer.
Thanks, it was helpful. Any other alternative?
If you just wanted to print a number with leading zeros, you could set the fill character to '0' and set the required field width.

But that is not useful in this case as you'd have to store the number of leading zeros (or the length of the data) entered by the user in a separate field.

So stick with using a string, it is more appropriate for this kind of data, which is actually a sequence of individual digits, rather than a single integer.
Last edited on
Topic archived. No new replies allowed.