Skip to content

Input/Output

Input Function

The function to read user input is the scanf function.

Function Prototype

scanf Prototype
1
2
3
4
int scanf(string format, ...);

// Common Usage
int scanf(format string, input list); // Assign to variables in list

Firstly, all user inputs are read as string. The parameter format specifies how the input string should be treated. This is done by specifying the format specifiers which are placeholders for values to be read.

Format Specifiers

Placeholder Variable Type Function Use
%c char printf/scanf
%d int printf/scanf
%f float/double printf/scanf
%f float printf
%lf1 double scanf
%e float/double printf (scientific notation)

Secondly the ... can take in zero or more optional parameters. If they are given, the parameters should be an address to a variable. The variable will be assigned the value on the placeholders based on its position. So, the first optional variable will be assigned the value on the first placeholder, the second optional variable will be assigned the value on the second placeholder, and so on.

The address of a variable can be obtained by using the address operator &. For instance, given a variable x, its address can be obtained using the expression &x.

Note that scanf has a return value of type int. This return value actually indicates the number of items in the ... that has successfully been assigned a value. However, in most cases, we assume that we have managed to read all and will typically ignore this value.

Lastly, the input will only be processed by scanf when the user press Enter.

Output Function

The function to display output on the monitor is the printf function. Its function prototype is

Function Prototype

printf Prototype
1
2
3
4
5
int printf(string format, ...);

// Common Usage
int printf(format string);             // Print string
int printf(format string, input list); // Print values in list

Firstly, the return value int is often ignored as it is simply the number of actual characters being printed on the screen.

Secondly, unlike scanf, we can specify more information for the format specified in printf.

For int, we can specify the minimum width to be displayed using %nd where n is an integer. For instance, %5d displays an integer in a width of 5. If there are fewer digits than the width, the number will be right justified.

For float/double, we specify two numbers separated by a decimal point (i.e., a dot) to specify the width and the number of decimal places. In this case, using the format %n.mf, n is the width and m is the number of decimal places. For instance, %8.3f displays a real number with total width of 8 including the 3 decimal places. Similar to the case of int, the number will be right justified.

Quick Quiz

How would you print a double with 4 digits after the decimal point and a minimum of 5 characters before the decimal point. Write the format speficier.

%10.4f

Examples

Multi Lines Input

Multi Lines Input

InputV1.c
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <stdio.h>
int main(void) {
  int age;
  double cap; // cumulative average point

  printf("What is your age? ");
  scanf("%d" , &age); // address of variable age
  printf("What is your CAP? ");
  scanf("%lf", &cap); // address of variable cap

  printf("You are %d years old and your CAP is %f\n", age, cap);

  return 0;
}

So how do we understand the example above?

Explanation

First, let's look at the first printf at line 6:

Line 6
1
printf("What is your age? ");

This line is the simplest because it has no additional argument. It will simply print the following on your monitor. Note that there is no newline printed and there is an additional space after the question mark.

1
What is your age? 

The next line is a scanf.

Line 7
1
scanf("%d" , &age);

This line will block the execution of your program until the Enter key is pressed. You should type a number here. After you pressed Enter, your screen will show a newline. What will then happen is the following:

  1. The number is read as a string "20".
  2. The string is compared with the placeholder "%d".
    • The placeholder expects a decimal integer (due to %d).
    • This matched with the input "20".
    • This number is then extracted as an integer.
  3. The number is then assigned into the variable age.
    • This variable is chosen because %d is the first placeholder and age is the first additional argument (_given as &age).

So now, the variable age has a value of 20. You probably will see something like the following on your screen.

1
What is your age? 20

The next line is another print.

Line 8
1
printf("What is your CAP? ");

At this point, your screen will probably look like the following:

1
2
What is your age? 20
What is your CAP? 

The next line is another scanf.

Line 9
1
scanf("%lf" , &cap);

Similar to line 7, but now we are reading a double since the placeholder is %lf. Try entering 5.0 and press Enter.

1
2
What is your age? 20
What is your CAP? 5.0

This is the last print.

Line 8
1
printf("You are %d years old and your CAP is %f\n", age, cap);

Now that both age and cap have a value of 20 and 5.0 respectively, we can print these values. This is the first example with multiple placeholders. The first is %d and the second is %lf.

The function printf will look at the additional arguments according to their positions. In this case, the first additional argument is age and the second additional argument is cap. This will be matched with the placeholder according to the position.

  • age%d
  • cap%f

The string being printed will then be:

"You are 20 years old and your CAP is 5.0\n".

Note that you may see more 0s being printed after 5.0 because C will try to print as many digits as possible.

1
2
3
What is your age? 20
What is your CAP? 5.0
You are 20 years old and your CAP is 5.0

Single Line Input

Single Line Input

InputV2.c
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <stdio.h>
int main(void) {
  int age;
  double cap; // cumulative average point

  printf("What is your age and CAP? ");
  scanf("%d %lf" , &age, &cap); // &age <--> %d and &cap <--> %lf

  printf("You are %d years old and your CAP is %f\n", age, cap);

  return 0;
}

The explanation is similar to multi lines input. However, for line 7, we should highlight that the scanf expects two values since it has two placeholders %d and %lf on the same function call. These two values have to be separated by a space. For instance, try putting in 20 and 5.0 as shown below.

1
What is your age and CAP? 20 5.0
  • The first value 20 match the first placeholder %d which will be assigned to the first additional argument age.
  • The second value 5.0 match the second placeholder %lf which will be assigned to the second additional argument cap.

Special Characters

Like other modern languages, C uses escape sequence in printf for characters that otherwise cannot be represented properly. The common escape sequences are shown below.

Sequence Meaning Result
\n New line Subsequent output will appear on the next line
\t Horizontal tab Move the cursor to the next tab position on the current line
\" Double quote Display a double quote "
%% Percent Display the percent character %
CRLF

There are actually two kinds of new line stemming from an old teletype "terminal"

  • \r: Carriage return (CR) commands the cursor to go back to the left-most position (i.e., the start).
  • \n: Line feed (LF) commands the screen to scroll up by one line.

Typewriter

In the older days of mechanical typewriter, we have to perform both manually. As we move to the electronic era, some conventions carry over to ease the transition.

The unfortunate side-effect is that we have several different conventions for new line depending on the operating system:

  • MacOS: \r
  • Windows: \r\n
  • UNIX: \n
Quick Quiz

How would you print a backslash?

\\

Exercises

Exercise

Have you ever been to a canyon before? If you have, you may have noticed that if you yell into the canyon, you will hear an echo of your own void. For instance, if you yell this module number --2100-- you will hear the echo back three times. Since you will also hear the number you are yelling, you will hear:

2100 2100 2100 2100

Write a C program to read an integer number and print the number exactly 4 times. Do not forget to terminate your output with a newline.

Sample Run 1

Input
1
2100
Output
1
2100 2100 2100 2100

Sample Run 2

Input
1
1
Output
1
1 1 1 1

We will focus on the main part of the answer. Hopefully, you can incorporate this into a complete C program.

Answer
1
2
3
int user_input; // good practice to write meaningful name
scanf("%d", &user_input);
printf("%d %d %d %d\n", user_input, user_input, user_input, user_input);

  1. %lf is long float, i.e., the longer version of float which is double. The reason why it has different placeholder is because scanf deals with pointer of any type. Since the representation for float differs from double, C will need to know exactly which of these to use especially when they have different size. On the other hand, for printf, C can simply convert everything to double before continuing so there is no need for two separate placeholders.