Printf

How to print some stuff on the screen

Standard Input / Output

#include <stdio.h> // std = STanDard, io = Input Output

A program communicates with the outside using standard input and standard output. The most common ways to input and output in C, are reading and writing to and from the console and files.

Console Output

We can use the function printf() from <stdio.h> to print to the console, as shown in the Hello World example. According to [cppreference][cppref_printf] (referencing a C++ site here because C++ reference is not publicly available, you have to pay ISO to get a copy), the signature of the function is:

int printf ( const char * format, ... );

The function returns the number of characters written.

How to print some words

Example 1 :

Your code:

printf("Hello World!");

Your screen:

Hello World!

Example 2 :

Your code:

printf("Hello");
printf("Hi");// it will continue to print behind whatever you printed earlier

Your screen:

Your code:

Your screen:

Format string

The first parameter is the format string. Ordinary characters can be directly printed, but the % character followed by flag characters is used to specify a substitute with a value when the string is printed. To specifically print out one % character, one must escape it using "%%".

The remaining ... means one or more parameters, specifically the value to be printed, ordered accordingly to the specifiers in the format string.

%d tells the computer to print the things inside the box with integers

Below is a table for the commonly used ones:

Specifier
Explanation

%%

Writes one % character

%c

Writes a character

%d

Writes an integer

%x

Writes an integer in base 16

%f

Writes a floating point number

The above table is very crude, so please refer to [cppreference][cppref_printf] for the complete explanation.

The following is an example:

More examples

classwork-03a

Last updated