C Programming/Simple input and output

(Redirected from C Programming/Simple Input and Output)
Previous: Variables C Programming Next: Simple math

Machines process things. We feed stuff into a machine and get different stuff out. A saw turns trees into planks. An internal combustion engine turns gasoline into rotational energy. A computer is no different. But instead of physical materials, computers process information for us.

We feed information into the computer, tell the computer what do with it, and then get a result back out. The information we put into a computer is called input and the information we receive from the computer is called output. Input can come from just about anywhere. Keystrokes on a keyboard, data from an internet connection, or sound waves converted to electrical signals are examples of input. Output can also take many forms such as video played on a monitor, a string of text displayed in a terminal, or data we save onto a hard drive. The collection of input and generation of output is known under the general term, input/output, or I/O for short, and is a core function of computers.

Interestingly, the C programming language doesn't have I/O abilities built into it. It does, however, provide us with an external library containing I/O functions which we can compile and link into our programs. We have already used an output library function in the Hello, World! example at the beginning of this text: printf(). You may recall this function resided in the stdio.h library file. As that file's name implies, stdio.h contains standardized I/O functions for adding input and output capability to our programs. This section of the text will explore some of these functions.

Output using printf()


Recall from the beginning of this text the demonstration program duplicated below:

#include <stdio.h>

int main(void)
     printf("Hello, World!");
     return 0;

If you compile and run this program, you will see the sentence below show up on your screen:

  Hello, World!

This amazing accomplishment was achieved by using the function printf(). A function is like a "black box" that does something for you without exposing the internals inside. We can write functions ourselves in C, but we will cover that later.

You have seen that to use printf() one puts text, surrounded by quotes, in between the parentheses. We call the text surrounded by quotes a literal string (or just a string), and we call that string an argument to printf.

As a note of explanation, it is sometimes convenient to include the opening and closing parentheses after a function name to remind us that it is, indeed, a function. However usually when the name of the function we are talking about is understood, it is not necessary.

As you can see in the example above, using printf() can be as simple as typing in some text, surrounded by double quotes (note that these are double quotes and not two single quotes). So, for example, you can print any string by placing it as an argument to the printf() function:

  printf("This sentence will print out exactly as you see it...");

And once it is contained in a proper main() function, it will show:

  This sentence will print out exactly as you see it...

Printing numbers and escape sequences


Placeholder codes


The printf() function is a powerful function, and is probably the most-used function in C programs.

For example, let us look at a problem. Say we want to calculate: 19 + 31. Let's use C to get the answer.

We start writing:

#include <stdio.h> // this is important, since printf
                   // can't be used without this header

int main(void)
    printf("19+31 is");

But here we are stuck! printf() only prints strings! Thankfully, printf has methods for printing numbers. What we do is put a placeholder format code in the string. We write:

    printf("19+31 is '''%d'''", 19+31);

The placeholder %d literally "holds the place" for the actual number that is the result of adding 19 to 31.

These placeholders are called format specifiers. Many other format specifiers work with printf(). If we have a floating-point number, we can use %f to print out a floating-point number, decimal point and all. Other format specifiers are:

  • %d - int (same as %i)
  • %ld - long int (same as %li)
  • %f - float
  • %lf , %g - double[1]
  • %c - char
  • %s - string
  • %x - hexadecimal

A complete listing of all the format specifiers for printf() is on Wikipedia.

Tabs and newlines


What if, we want to achieve some output that will look like:

  312 +

printf() will not put line breaks in at the end of each statement: we must do this ourselves. But how?

What we can do is use the newline escape character. An escape character is a special character that we can write but will do something special onscreen, such as make a beep, write a tab, and so on. To write a newline we write \n. All escape characters start with a backslash.

So to achieve the output above, we write:

    printf(" 1905\n312 +\n-----\n");

or to be a bit clearer, we can break this long printf statement over several lines. So our program will be:

#include <stdio.h>

int main(void)
    printf(" 1905\n");
    printf("312 +\n");
    printf("%d", 1905+312);
    return 0;

There are other escape characters we can use. Another common one is to use \t to write a tab. You can use \a to ring the computer's bell, but you should not use this very much in your programs, as excessive use of sound is not very friendly to the user.

Other output methods




The puts() function is a very simple way to send a string to the screen when you have no placeholders or variables to be concerned about. It works very much like the printf() function we saw in the "Hello, World!" example:

    puts("Print this string.");

will print to the screen:

  Print this string.

followed by the newline character (as discussed above). (The puts function appends a newline character to its output.)

Input using scanf()


The scanf() function is the input method equivalent to the printf() output function - simple yet powerful. In its simplest invocation, the scanf format string holds a single placeholder representing the type of value that will be entered by the user. These placeholders are mostly the same as the printf() function - %d for integers, %f for floats, and %lf for doubles.

There is, however, one variation to scanf() as compared to printf(). The scanf() function requires the memory address of the variable to which you want to save the input value. While pointers (variables storing memory addresses) can be used here, this is a concept that won't be approached until later in the text. Instead, the simple technique is to use the address-of operator, &. For now it may be best to consider this "magic" before we discuss pointers.

A typical application might be like this:

#include <stdio.h>

int main(void)
    int a;

    printf("Please input an integer value: ");
    scanf("%d", &a);
    printf("You entered: %d\n", a);

    return 0;

If you were to describe the effect of the scanf() function call above, it might read as: "Read in an integer from the user and store it at the address of variable a ".

If you are trying to input a string using scanf, you should not include the & operator. The code below will produce a runtime error and the program will likely crash:

    scanf("%s", &a);

The correct usage would be:

    scanf("%s", a);

This is because, whenever you use a format specifier for a string (%s), the variable that you use to store the value will be an array and, the array names (in this case - a) themselves point out to their base address and hence, the address of operator is not required.

Note that using scanf() to collect keyboard input from the user can make your code vulnerable to Buffer overflow issues and lead to other undesirable behavior if you are not very careful. Consider using fgets() instead of scanf().

Note on inputs: When data is typed at a keyboard, the information does not go straight to the program that is running. It is first stored in what is known as a buffer - a small amount of memory reserved for the input source. Sometimes there will be data left in the buffer when the program wants to read from the input source, and the scanf() function will read this data instead of waiting for the user to type something. Some may suggest you use the function fflush(stdin), which may work as desired on some computers, but isn't considered good practice, as you will see later. Doing this has the downfall that if you take your code to a different computer with a different compiler, your code may not work properly.


  1. Actually %f prints doubles as well, but the use of %f for input is different. For more details, see the Wikipedia article on C data types.
Previous: Variables C Programming Next: Simple math