Sean has a Bachelor's Degree in Physics and has taught Computer Science courses as a Graduate Assistant.
Basic Input & Output in C Programming
Basic Input vs Output
Input and output is terminology referring to the communication between a computer program and its user. Input is the user giving something to the program, while output is the program giving something to the user.
Let's say we're stuck in the waiting room at the doctor's office, and we get hungry. Oh look, a vending machine! We're saved! Well, we might not get that excited, but let's get a snack. We'll input $2 into the vending machine, and it will output a bag of chips. This is a very simple and straightforward form of input and output. Put something into a machine, and it puts something back out.
Simple Vending Machine Program
In programming, the most basic form of input/output (I/O) is displaying some text to a user and allowing the user to enter some text back. For example, let's say we wanted to write a simple vending machine program where the user inputs a selection from a menu, and the vending machine outputs the name of the product selected.
Well, first let's add a menu. We want to keep it simple, so let's make it look like what's appearing here:
Vending Machine Menu
1 - Chips
2 - Peanuts
3 - Popcorn
4 - Cookie
5 - Drink
In C programming, the most basic function to output text to the screen is printf(). So let's write a program in C that simply displays our menu and exits. We will use the printf() function.
#include <stdio.h>
int main( ) {
char products[5][10] = {"Chips", "Peanuts", "Popcorn", "Cookie", "Drink"};
printf("Vending Machine Menu\n\n");
for(int i = 0; i < 5; i++) {
printf("%d - %s\n", i+1, products + i);
}
return 0;
}
There's a lot going on here, so let's look at it line by line, starting with the header files.
Header Files
Let's look at the first line:
#include <stdio.h>
This line includes the header file for the basic input and output functions of the C standard library. Lines like this will appear at the top of C programs to add some extra functionality. In our case, we need some basic input and output functions, so we use the stdio.h header file. I won't go into more detail on the standard library and header files as it's beyond the scope of this lesson, but including header files gives us access to functions that we won't have to write for ourselves. At least one header file will be included in almost every C program.
Main Function
Now, let's look at the main function:
int main( ) {
This line creates the main() function, which will be executed when we run a C program. It's generally good practice to write other functions that can be called from within the main() function, but for a simple program like this, including the code in the main() function itself is generally acceptable.
The Code
Now, let's look at the code itself. In the first couple of lines, we're setting up our program to run. We will see those lines in nearly every C program. Now that we're inside the main() function, we can look at what our program will actually do:
char products[5][10] = {"Chips", "Peanuts", "Popcorn", "Cookie", "Drink"};
Here we create an array of products that can be purchased from the vending machine. We can think of an array as a numbered list. When we create the array, it's similar to tearing off a sheet of paper and numbering it. We can then fill in the list of items in any order we want. In almost all programming languages, an array is defined and accessed using brackets. In C programming, a string is created and stored as an array of characters, like this:
char somestring[10] = "some text";
This statement creates an array of characters called somestring to hold the string "some text". If we want to access the values in our array, we can do so by using the index, which is the number for each item in the list. However, instead of starting at one like a numbered list would, the index starts at zero. So if we want to access the first thing in our array, we'll want the item at index zero. We can access the first character in somestring by using the following code:
somestring[0];
The first item in somestring is the first character in "some text", so when the above reference is used it will return the character "s".
Okay, back to our vending machine program. We were looking at the first line:
char products[5][10] = {"Chips", "Peanuts", "Popcorn", "Cookie", "Drink"};
Notice the double set of brackets after products in the code. Since a string is an array of characters in C, we create an array of arrays in order to create an array of strings. Here we are creating the array products to hold 5 strings, each with a maximum length of 10, and filling in all 5 values with the product names we want in our menu.
printf("Vending Machine Menu\n\n");
When you pass a string to the printf() function as a parameter, that string (minus the quotation marks) will be displayed on the screen. In this case, we will use the function to output "Vending Machine Menu". The two line breaks (\n\n) at the end allow us to move to a new line below our menu heading:
for(int i = 0; i < 5; i++){
On this line, we start a loop that will run 5 times so that we can go through our product list:
printf("%d - %s\n", i+1, products + i);
Each time we go through the loop, we will use printf() to display a line about the corresponding product. The %d and %s inside the first parameter are placeholders. These will be replaced with values that we want to insert into the output. The function will go through these placeholders and replace them, in order, with the parameters that follow. The %d is a placeholder for an integer value; in this case, we will be displaying the number of the product. The %s is a placeholder for a string; in this case, the product description will be displayed.
Format Specifiers
Now, let's look at the format specifiers. The %s and %d are called format specifiers, and, as their name suggests, they are used to specify the format of input or output.
The four most common format specifiers are in this chart:
Format Specifier | Data Type |
---|---|
%s | string |
%c | character |
%d | int |
%f | float |
We will generally see these used any time we do input/output in a program.
Now to the last line of our program:
return 0;
This line exits our main() function. By returning 0 as our exit code, we are sending the message that everything completed without error. And if we run our program, we will see this:
Vending Machine Menu
1 - Chips
2 - Peanuts
3 - Popcorn
4 - Cookie
5 - Drink
Great! This is exactly what we wanted. Now it's time to let the user enter a selection.
Taking Input
Now, let's look at taking input. Let's add the following lines to our program:
printf("\n\n");
printf("Please enter a selection (1 - 5): ");
int selection = -1;
scanf("%d", &selection);
The first line here just moves down a couple of lines on our output to make things a little less jumbled up. Next, we prompt the user to enter a selection from the menu we've provided. The third line creates a variable selection to hold the value that the user enters. And, the last line uses the scanf() function to take in the input from the user.
The first parameter in scanf() takes a format specifier (inside quotation marks), and the second takes a pointer to a variable, which is where we want to store the input. So in this case, we are expecting an integer value to be entered, and we will store it in the selection variable we created on the previous line.
Okay, so now we know what snack our user wants! Let's finish up by displaying the selection back to the user:
printf("\n\nYou've selected %s, an excellent choice!\n\n", products + (selection - 1));
Here we use some line breaks to make things look a little nicer, then we use the %s placeholder for the selected product and use the selection variable that the user entered to specify what product they want. Here's what the whole program looks like:
#include <stdio.h>
int main( ) {
char products[5][10] = {"Chips", "Peanuts", "Popcorn", "Cookie", "Drink"};
printf("Vending Machine Menu\n\n");
for(int i = 0; i < 5; i++){
printf("%d - %s\n", i+1, products + i);
}
printf("\n\n");
printf("Please enter a selection (1 - 5): ");
int selection = -1;
scanf("%d", &selection);
printf("\n\nYou've selected %s, an excellent choice!\n\n", products + (selection - 1));
return 0;
}
Now if we run our program, we'll see something like this:
Vending Machine Menu
1 - Chips
2 - Peanuts
3 - Popcorn
4 - Cookie
5 - Drink
Please enter a selection (1 - 5): 2
You've selected Peanuts, an excellent choice!
This looks great! We've shown our user a menu, allowed them to select one of the items, and confirmed their selection.
Validating Input
Now, let's look at validating input. But what if our user didn't make a valid selection? Maybe they misread our menu or just mistyped their selection. We'll want to let them know they didn't make a valid selection and give them another chance. We can do that with a while loop:
printf("Please enter a selection (1 - 5): ");
int selection = -1;
scanf("%d", &selection);
while(selection < 1 || selection > 5) {
printf("\n\nSorry, you've made an invalid selection! Please select using only the numbers 1 through 5.\n\nPlease enter a selection (1 - 5): ");
scanf("%d", &selection);
}
The program will repeat the code inside the while loop while the condition inside the parentheses is true. So while the selection is less than one (selection < 1) or (||), the selection is more than 5 (selection > 5). While the user's selection is not between one and five, the code inside will continue to be executed. This means the user will have to keep entering values until they enter a value between 1 and 5.
This works great if the user enters any number. If it is outside the range we want, the program will prompt that they've made a mistake and should try again. However, if they enter something besides a number, we will have a problem. Our program will go into an infinite loop and we will have to forcibly terminate it (throwing our laptop against a wall is a reasonable solution).
To understand why this happens, we need to understand exactly how scanf() works. The scanf() function gets the user's input from a temporary storage space called an input buffer. When the user enters something using the keyboard, whatever they typed is stored in this input buffer where scanf() can read it.
When scanf() finds input that matches the format specifier provided (%d for an integer in this case), it clears the input buffer and we move along happily with a clean slate for the next input. However, if scanf() doesn't find matching input, it leaves the buffer intact so that it can be read again.
So if, for example, at our menu we enter "peanuts" instead of entering "2", the next time we try to use scanf() it will still see "peanuts" in the input buffer. So if we keep trying to read an integer from the input buffer using scanf(), it will keep leaving "peanuts" in the buffer. This is because, contrary to popular belief, "peanuts" is not an integer.
So, what we need is to clear out this input buffer manually. We only need to do this if the user didn't make a valid selection, and we need to do it every time. So inside the while loop, and before we use scanf() to try and get another input, we'll insert the line appearing here:
while(getchar() != '\n');
The getchar() function is another function that reads from the input buffer. It reads and removes the first character from the input buffer. We use a while loop to continue using getchar() to remove characters from the input buffer until we get to the end of the line of input, which will be a line break character (\n). Notice that there is no body to this while loop. We don't need to do anything every time a character is removed from the input buffer, just remove all of them.
Now, let's put it all together:
#include <stdio.h>
int main( )
{
char products[5][10] = {"Chips", "Peanuts", "Popcorn", "Cookie", "Drink"};
printf("Vending Machine Menu\n\n");
for(int i = 0; i < 5; i++)
{
printf("%d - %s\n", i+1, products + i);
}
printf("\n\n");
printf("Please enter a selection (1 - 5): ");
int selection = -1;
scanf("%d", &selection);
while(selection < 1 || selection > 5)
{
while(getchar() != '\n');
printf("\n\nSorry, you've made an invalid selection! Please select using only the numbers 1 through 5.\n\nPlease enter a selection (1 - 5): ");
scanf("%d", &selection);
}
printf("\n\nYou've selected %s, an excellent choice!\n\n", products + (selection - 1));
return 0;
}
Lesson Summary
That was quite a bit for us to cover, so let's review the important information that we've learned. In this lesson, we first reviewed input, which is the user giving something to the program, and output, which is the program giving something to the user. Then, we learned how to use them.
We used the printf() and scanf() functions to create a simple vending machine program that displays a list of snacks and allows a user to enter a selection from the menu. We made sure the user made a valid choice and then gave the user some feedback, confirming what they selected. The best part of our program though is, undoubtedly, the free snacks!
To unlock this lesson you must be a Study.com Member.
Create your account
Register to view this lesson
Unlock Your Education
See for yourself why 30 million people use Study.com
Become a Study.com member and start learning now.
Become a MemberAlready a member? Log In
Back