C Study Guide

St. Gabriel's College

|

Input and Output

Input is how we get information from the person using our program. Output is how we write information to the screen. In order to do Input and Output, you must include the header file stdio.h at the beginning of your program.

Output

The easiest way to do output is with the printf() function, like this:

printf("Hello World!");

When using printf(), you can include variables in your output by using format strings:

printf("Your name is %s and your age is %d.", name, age);

The following format strings are used by printf() and scanf() for dealing with variables:

It’s also important to use Escape characters to make your output look the way you want it to. Escape characters make it easier to talk about characters that are "invisible" or hard to write out. Here are a few examples of Escape characters:

Input

There are a few functions we can use for input. The first one we will talk about is scanf():

scanf("%d", &age);

This function can read input and is like the opposite of printf(). However, it also has some problems you need to know about:

A better idea is to use fgets():

fgets(string, 1000, stdin);

This will read one line of input and store it in the String. If you needed an int or float, you can get them using the atoi() (Alpha to Integer) and atof() (Alpha to Floating-Point) functions like this:

char string[1000];

printf("Enter your age: ");
fgets(string, 1000, stdin);
int age = atoi(string);

printf("How much money do you have? ");
fgets(string, 1000, stdin);
float money = atof(string);

This is a safer way to do input. If you only want to read one character, the getchar() function is also a good one to use:

printf("What is your grade?");
char grade = getchar();

Whether you want to use scanf() or fgets() or getchar() is up to you. Use the one that works best for you.

Input/Output Buffers

When a user types input, it is stored in a Buffer. When the user presses the Enter key, the line they typed is added to the Input buffer. If your input function does not read the whole line, it will leave extra text in the buffer, which will be used the next time you use an input function. Here's an example program, which uses getchar() to read the first letter of the input:

Code:
char choice1, choice2; printf("1+1=? Choose:\nA - 1\nB - 2\nC - 4\nD - I don't know\n"); choice1 = getchar(); printf("2+2=? Choose:\nA - 3\nB - 4\nC - 8\nD - I don't know\n"); choice2 = getchar();

Input Buffer:
I don't know\n

How can you fix this? If you're going to use a function like getchar() or scanf(), you have to clear the buffer. One way to do this is with a loop, like this:

Code:
char choice1, choice2, clear = ' '; printf("1+1=? Choose:\nA - 1\nB - 2\nC - 4\nD - I don't know\n"); choice1 = getchar(); while(clear != '\n') clear = getchar(); printf("2+2=? Choose:\nA - 3\nB - 4\nC - 8\nD - I don't know\n"); choice2 = getchar();

Input Buffer: