Learning C-Style C++


by Direct Approach Mentoring



printf(
"%d"
,number)

6. Variable Screen Output

There are two extremely good reasons for outputting to the screen:
  1. Show the end user information, or the results of your program, or the visuals in a game, etc.
  2. Show yourself what the hell's going on as your program runs.
Do not be afraid to print stuff to the screen A LOT. It won't hurt but it can help you understand what's going on in your program.

If you ever have an area of malfunctioning code, try printing out the values as it runs to see what's happening. This is an excellent way to troubleshoot.


Let's say you have an

int

called

n

and you want to print its value to the screen. Try something like this:

int

n;
. . .
printf(
"The value of n is %d at this moment."
, n );



Notice the %d above.

printf

checks the string you give it for any format tags. A format tag is some text that starts with a percent sign (%) and is (usually) followed by one letter.

printf

will replace any format tags it finds with the values in variables of your choice. Format tags only work in strings you send to printf. They are your way to tell printf what you want it to do.

Let's say we want to print out the values in 3 different kinds of variables, a number, a decimal, and a character:

int

number;

float

dec;

char

c;
. . .
printf(
"Number: %d   Decimal: %f   Character: %c"
, number, dec, c );



The order has to match!
If the string uses

int

,

float

,

char

then the list of variables after the string must also be

int

,

float

,

char

.



Next: 7. Input