• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

A little C++ help for a newb...(formatting output)

Amber

Senior member
Hi,

I am wondering if there is a way (I'm sure there is) to display the following correctly:

I have a user enter a two digit number, say 01, 02,...45...


int id = 0;

cout << "Please enter #: ";
cin >> id;

cout << "#: " << id << endl;

If the number is 01 through 09 it only displays 1-9 without the preceding 0.

I've scoured my book that I have and used google a bit and I can't seem to find an answer.

Anyone know how to correct this?

Thanks from a c++ newb. 🙂
 
There is a way:

if (id<10)
cout <<"#: 0" <<id <<endl;
else
cout <<"#: " <<id <<endl;

This is not exactly the best way but it works 😛

I think there is a fill() function that can be used in conjunction setw() but I am no expert.

Try this link
 
A similar way of doing it would be with the conditional operator.

(condition ? expression1 : expression2)

cout << "#:" << (id < 10 ? "0" : "") << id << endl;

If id is less than 10 it will print out a 0 and if it's greater than or equal to 10 it will print nothing.

edit: clarification
 
Originally posted by: Ligoc
A similar way of doing it would be with the conditional operator.

(condition ? expression1 : expression2)

cout << "#:" << (id < 10 ? "0" : "") << id << endl;

If id is less than 10 it will print out a 0 and if it's greater than or equal to 10 it will print nothing.

edit: clarification

The conditional operator is merely a short of an if-else statement. It works but it looks ugly and it's difficult to understand IMHO.
 
Originally posted by: Ligoc
A similar way of doing it would be with the conditional operator.

(condition ? expression1 : expression2)

cout << "#:" << (id < 10 ? "0" : "") << id << endl;

If id is less than 10 it will print out a 0 and if it's greater than or equal to 10 it will print nothing.

edit: clarification

Great, thanks. This is the one I ended up using. It seems like it was the cleanest way to do what I wanted.

I appreciate everyone's help! 🙂

(used Amber's SN)

 
Back
Top