|
Remember <stdio.h>? Ah yes, our header file for input and output. Well, lets look at a few things this file makes possible for us in our C programs. You should be familiar with printf( ) and how to go about printing words and numbers with it. Now we are going to learn about scanf( ) and the powers it holds.When we use input with the user, it is a good idea to set up a prompt that asks for something. Of course, this is done by printf( ). Lets make a simple program that asks the user for 2 numbers and a letter, then print them back to the screen using printf( ). We will have to use several variables to capture the users input, and use them to print back to the screen the users input.
DOWNLOAD PROGRAM
#include <stdio.h> int main(void) { char x; int y, z; printf("Enter a character: "); scanf("%c", &x); printf("\nEnter 2 numbers on the same line: "); scanf("%d %d", &y, &z); printf("\n\nYour input was %d, %d and %c.", y, z, x); return 0; }
First we declared a char variable x, and 2 ints y and z.
Reading characters
scanf("%c", &x);scanf is used to read in from the keyboard. The data you read in is then stored into a variable. In the above line a character was read in. Between the parentheses you write %c when you wish to read in a letter. After the comma you write &variable_name (in this case &x). Be sure the variable matches the type in which you are inputting designated by the %c.
If you were reading in an integer, you would write %d. If a floating point, %f.
Reading in multiple inputs on a single line
scanf("%d %d", &y, &z);This line read in the 2 int variables. The & symbol is refered to as the "address of" operator. It points to the computer address of y and z. You will learn more on this when we cover pointers. For now just remember to use & before your variable name when reading in with scanf.
CAUTION: when using scanf, the contents that were in the variable you read into are destroyed and replaced in that call. (Much like the assignment operator)