Introduction
Printf and scanf are 2 basic standard C functions that provide basic interaction between your program and an user. In order for a program to be useful, it must have some interactions with the user. These interactions generally consists of inputs and outputs (IO) via certain medium.
- Inputs refer to the contents provided to the program while outputs refer to the contents produced by the program.
- A medium could be a command line terminal, a file, network …etc.
Generate Outputs with printf()
printf() is a standard C function that prints an output on standard output
, (aka, your command line terminal). It is a flexible function that can work with many different data types and format outputs according to your preference. This is probably the most commonly used standard function for a developer and in fact most other standard C functions (such as sprintf()
, fprintf()
…etc) share similar usage as printf().
Printf() has this function prototype, where it can take multiple arguments (indicated by …) and produce a formatted output.
int printf(char *format, arg1, arg2, ...);
For example:
// output a number printf("these are numbers: %d %d %d\n", 168, 745, 549); // output a string - double quote is escaped with back slash printf("this is a string: \"%s\"\n", "hello"); // output a number as hexadecimal form printf("\tthese are hex numbers: %02X %02x 0x%02X", 168, 745, 549); // output a decimal number to 2 decimal places printf("this is a decimal number: %.2f\n", 3.1416);
The above will produce these outputs:
these are numbers: 168 745 549
this is a string: "hello"
these are hex numbers: AB 02e9 0x0225
this is a decimal number: 3.14
Format Specifier
In order to work with different variable data types, printf provides a list of possible format specifiers
to properly format an output. These format specifiers start with %
sign followed by a special character encoding according to the table below.
Specifier | Description | Example |
---|---|---|
%d or %i | signed integer | 168 or -168 |
%u | unsigned integer | 745 |
%o | unsigned octal | 610 |
%x | unsigned hexadecimal integer | 3ff |
%X | unsigned hexadecimal integer (upper case) | 3FF |
%02X | unsigned hexadecimal integer (upper case) – print in pair of 2 | 03FF |
%f | floating point number | 3.1416 |
%.2f | floating point number to 2 decimal places | 3.14 |
%F | floating point number (upper case). Normally the same as %f | 3.1416 |
%e | scientific notation | 3.1416e+4 |
%E | scientific notation (upper case) | 3.1416E+4 |
%g | same as %e or %f whichever is shortest | 3.14 |
%G | same as %E or %F whichever is shortest | 3.14 |
%a | Hexadecimal floating point | -0xc.90fep-2 |
%A | Hexadecimal floating point (upper case) | -0XC.90FEP-2 |
%c | single character | h |
%s | string of characters | hello |
%p | pointer address | 0x7ffee3e89a38 |
%% | to escape the % sign | % |
Refer to this article for more details.
Escape Sequence
You may use the following escape sequences to format printf() output
Escape Sequence | Description |
---|---|
\n | new line character |
\t | tab character |
\” | double quote |
\’ | single quote |
\\ | backslash character |
For example:
printf("This is a newline:\nThis is a tab:\tThis is a backslash:\\\n");
The above will produce this output:
This is a newline:
This is a tab: This is a backslash:\
Special Macros
You can use the following special Macros to print properties about the current source file. This is useful if you plan to use printf() as a logging facility.
- __FILE__: translates to current filename
- __LINE__: translates to current line number within the file
- __FUNCTION__: translates to current function name
Example: myreport.c:
void reportError(void) { printf("%s:%s:%d - critical error detected"); }
The above will output:
myreport.c:reportError:3 - critical error detected
Gather Input with scanf()
scanf()
is a standard C function that is commonly used to read from standard input stream (stdin
) to format user’s input data into one or more variables. scanf()
is often used as the counterpart to printf
, which is used for formatted output. It has the below function prototype:
int scanf(const char *format, ...)
For example: the code below will wait for the user to provide an input that consists of 3 values separated by 2 spaces. First value should be formatted as integer and stored in mynumber
, second value should be formatted as a string stored in mystring
and third value should be formatted as float number stored in myfloat
.
int mynumber=0; char mystring[20] = {0}; float myfloat = 0.0; // program will pause here until user has sent some inputs scanf("%d %s %f", &mynumber, &mystring[0], &myfloat);
Combine printf() and scanf() …
Printf and scanf can be combined together to gather user’s inputs.
void promptAndPrint(void) { int iNumber = 0; int mynum = 99; printf("%s:%s:%d | Enter an integer please: ex: %d, %d or %d:", __FILE__, __FUNCTION__, __LINE__, 34, -25, mynum); scanf("%d", &iNumber); printf("You entered: %d\n", iNumber); }
Hi, this is Cary, your friendly tech enthusiast, educator and author. Currently working as a software architect at Highgo Software Canada. I enjoy simplifying complex concepts, diving into coding challenges, unraveling the mysteries of software. Most importantly, I like sharing and teaching others about all things tech. Find more blogs from me at highgo.ca
Pingback: Create Custom Data Types With the C Struct - techbuddies.io
Pingback: Beware of Type Casting in C - How to do it Right - techbuddies.io
Pingback: Working with the Infamous Strings in C Made Easy - techbuddies.io