The while loop at line 24 is key here.
This condition
while(s > 0)
can be read as "while at least one of the remaining digits is non-zero". That is the precise cause of the symptoms you are getting.
If you're not sure what is happening, use a debugger, or insert additional cout statements to display some or all of the key variables from within the loop.
If line 35
cout << o;
is temporarily replaced with this debugging code,
35 36
|
//cout << o;
cout << "\nh: " << h << " s: " << s << " p: " << p << " o: " << o;
|
We get this output:
Provide decimal value: 257
Hexadecimal equivalent:
h: 1 s: 1 p: 16 o: 1
h: 0 s: 1 p: 1 o: 0
h: 1 s: 0 p: 0 o: 1
Provide decimal value: 256
Hexadecimal equivalent:
h: 1 s: 0 p: 16 o: 1 |
Notice the value of "s" in each case. In the second, where the input was 256, s becomes zero on the first iteration, and hence just a single digit is output.
However, what is more interesting is the value of p. Notice in the first case (input 257, which worked), p becomes zero at the same stage as s.
What is required is to go around the loop until the lowest-order digit has been output. Luckily in this case the solution is really simple. Change the condition at line 24 to
while (p > 0)
(and take out the debugging code of course).