### How to convert 1 to 01?

I have an integer in a vector and I need to convert it from a single digit (1,2,3,...9) to a single digit with a 0 in front of it (01,02,03,...09). How would I do that?

 ``123456789`` `````` for(int i=0;i<5;i++) { if(vector[i] == 1 || 2 || 3 || 4 || 6 || 7 || 8 || 9) { ..... } } ``````
The "01" format is only useful for printing out and reading strings. Internally, an int is an int is an int.

To print an int with '0' padded on the front, try:

 ``1234`` ``````int x = 1; char oldFill = std::cout.fill('0'); std::cout << setw(2) << x; std::cout.fill(oldFill); // restores old value ``````

But you have additional problems with line 4. What you want is
 ``12345678`` ``````if(vector[i] == 1 || vector[i] == 2 || vector[i] == 3 || vector[i] == 4 || vector[i] == 6 || vector[i] == 7 || vector[i] == 8 || vector[i] == 9)``````

Your statement compared vector[i] with 1, and then or'ed it with the values 2, 3, etc., each treated like a boolean. Since any value other than 0 treated like a bool is true, your statement evaluates to

`if (vector[i] == 1 || true || true || true || ...)`

which will always evaluate to true.
Hi

Why do you need the leading 0?

I think you are probably talking about displaying a number with a leading 0?

If you are familiar with std::ostream (like cout) then check out

setw
http://www.cplusplus.com/reference/iostream/manipulators/setw/

setfill
http://www.cplusplus.com/reference/iostream/manipulators/setfill/

Or would you prefer to use printf/sprintf?

Andy
Last edited on
Thanks doug4 for the heads up with the ==.

I'm trying to get the "]" to all line up when they get printed. The vector has randomized int's from 1 to 15, so when they get printed the single digit and double digit int's make it so they don't line up vertically.

 ``123456789101112131415`` `````` for(int i=0;i<5;i++) { if(vector[i] = 1 || 2 || 3 || 4 || 6 || 7 || 8 || 9) { ..... } } cout << "[ " << vector[0]<< " ] << endl; cout << "[ " << vector[1]<< " ] << endl; cout << "[ " << vector[2]<< " ] << endl; cout << "[ " << vector[3]<< " ] << endl; cout << "[ " << vector[4]<< " ] << endl; ``````

I guess I gotta use the setw and setfill, I'm just not sure how to apply it in this context.
Last edited on
Lol , if i have not got it wrong , a simple condition could do your job :D
 `` `` ``if (vectorB[i]<10) cout<<"0"<

NOTE:I have used 'i' , dont forget to replace it with whatever constant you want to use and also you could add those brackets before and after .
Last edited on
Thank you Maggi! The solution was soo simple, I feel like an idiot :)

Never mind , it happens sometimes :)
And since you are newbie let me tell you that you could mark this question as solved so others who browse here knows that this question is solved .
Topic archived. No new replies allowed.