Getting Input From The User

The next program we create is also not very sophisticated. However, it illustrates how to get input from the user and gives us an opportunity to describe more fully the printf function along with a number of user input functions.

The user input functions we shall meet are getchar, gets and scanf.

The first of these, getchar, is the simplest. It simply returns a single character of input from the user (i.e. a single keypress). The function gets retrieves a whole string of characters from the user. Finally, scanf also retrieves a string of data from the user, but does not expect just any old string of characters. You the programmer, can tell it how to scan (i.e. interpret) the data coming in, by specifying precisely what format it will take.

top

A User Input Program

Here is the program which we will analyse:

#include <stdio.h>

int main(void)
{
    int number1, number2;
    char keypressed;
    char buffer[20];
    
    printf("Please enter two integers separated by a comma, followed by ENTER: ");
    scanf(" %d , %d",&number1,&number2);getchar();
    printf("The first number you entered was: %d\n",number1);
    
    printf("Press a key to see the second number, followed by ENTER.\n");
    keypressed = getchar();getchar();
    
    printf("The second number was: %d. ",number2);
    printf("And the key you pressed was %c\n",keypressed);
    
    printf("Now enter your favourite colour: ");
    gets(buffer);
    printf("Yuck! %s is a terrible colour!\n",buffer);
    
    return 0;
}

Notice that this is just our basic program template with a whole lot of extra lines in it.

You have already seen printf, so the first line where this occurs is unremarkable, except that we have not included a \n. This is simply because in the very next expression, we get some input from the user by invoking the scanf function, and we do not want the user to be entering their input on a new line. Instead, whatever they type will appear on the same line of the screen as the printf message.