Skip to content

Input Output

Fábio Gaspar edited this page Jan 15, 2019 · 1 revision

The standard library stdio.h provides functions that allow you send and retrieve data from streams.

Printf

The printf function writes a C string to stdout (Standard Output), which usually will be displayed on terminal/console. However, the application output can be redirected to a file, for example.

The printf functions is defined on stdio.h library, and it's prototype is as follows: int printf ( const char * format, ... );

The function takes a variable number of arguments, where the first one is a C string. If that C string uses format specifiers (begin with %), the additional arguments are formatted and inserted in the resulting string.

For example:

int a = 5;
int b = 2;
float c = (float) 5/2;
printf("Operation %d/%d = %f", a, b, c);

Notice the that the string has three format specifiers (%d, %d and %f) and therefore three additional arguments (a,b,c). The first %d is replaced with the variable a value, the second %d with variable b value and the %f is replaced with c value.

So the string to be sent to Standard Output is:

Operation 5/2 = 2.5

There are several format specifiers. %d is used to print an integer value, %f for floats, %c for chars, etc. You can see more specifiers @ https://www.tutorialspoint.com/c_standard_library/c_function_printf.htm

The arguments don't have to be variables. Constants and expressions are also valid.

printf("Operation %d/%d = %f", 5, 2, 5/2);

Ouptut:

Operation 5/2 = 2.5

Scanf

The scanf function reads data from the stdin (Standard Input) in a formatted way. This allows you to get input from the user of the application.

The scanf definition is int scanf ( const char * format, ... ). The first argument is the C string where you put the format specifiers followerd by variables where the input is stored.

#include "stdio.h"

int main()
{
    int a, b;
    printf("Insert first operand: ");
    scanf("%d", &a); // the user inserts a number which will be stored on the variable `a`
    printf("Insert second operand: ");
    scanf("%d", &b); // notice the & operator. The scanf needs the variable address, not the variable value.
    printf("Sum: %d", a+b);
}