Skip to content
Home » All Posts » Create User Interactions with Printf and Scanf

Create User Interactions with Printf and Scanf

basic io with printf and scanf

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.

SpecifierDescriptionExample
%d or %isigned integer168 or -168
%uunsigned integer745
%ounsigned octal610
%xunsigned hexadecimal integer3ff
%Xunsigned hexadecimal integer (upper case)3FF
%02Xunsigned hexadecimal integer (upper case) – print in pair of 203FF
%ffloating point number 3.1416
%.2ffloating point number to 2 decimal places3.14
%Ffloating point number (upper case). Normally the same as %f3.1416
%escientific notation3.1416e+4
%Escientific notation (upper case)3.1416E+4
%gsame as %e or %f whichever is shortest3.14
%Gsame as %E or %F whichever is shortest3.14
%aHexadecimal floating point-0xc.90fep-2
%AHexadecimal floating point (upper case)-0XC.90FEP-2
%csingle characterh
%sstring of charactershello
%ppointer address0x7ffee3e89a38
%%to escape the % sign%
common format specifiers

Refer to this article for more details.

Escape Sequence

You may use the following escape sequences to format printf() output

Escape SequenceDescription
\nnew line character
\ttab 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);
}

Join the conversation

Your email address will not be published. Required fields are marked *