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.
The easiest way to do output is with the printf() function, like this:
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:
%f- Floating-Point Numbers
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:
\n- Newline (The Enter key)
\"- Use this if you want double quotes inside of a String.
\'- Use this if you want single quotes inside of a String.
\\- Use this if you want a backslash inside of a String.
\0- NULL character (We don’t use this very often)
There are a few functions we can use for input. The first one we will talk about is scanf():
This function can read input and is like the opposite of printf(). However, it also has some problems you need to know about:
- If the user inputs something that is the wrong type, scanf() will save the input and try to use it again the next time you call scanf().
- If the variable you want to read to is an int, char or float, you must put an ampersand (&) before the variable name.
If the variable you want to read to is a char, you must put a space before the %c, like this:
scanf(" %c", &grade);
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; 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.
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:
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: