Accepting User Input

2-minute read
Table of Contents

Notice how we have only been hard-coding values into our program. Often times we will want to have the user input these values. In C, we can use the function scanf() to accept values from the user. There are other functions, some of which we will address later on.

The basic format for using scanf() is:


scanf(format_string,address_1,address_2,...);

Take for example asking the user for their age:

#include <stdio.h>

int main(){
    int age;
    printf("Please enter your age: ");
    scanf("%d",&age);
    printf("Wow so you are %d years old huh?!\nDas crazyyy!!",age);
    return 0;
}
asking-for-age.c
Copy

The ampersand, &

We use the ampersand (&) to specify that we want to use the address (memory location) of the variable that follows. In this case, the variable is age. Scanf() requires the address of the variable in order to update/change its value. This is unlike printf() which takes a copy of the variable (no ampersand is needed in order to get a copy).

Printing the memory address of a variable

It is good to know the placeholder/format specifier to print memory addresses in C:

#include <stdio.h>

int main(){
    char character;
    printf("Please enter a character: ");
    scanf("%c",&character);
    printf("The character you entered (%c) is now located at %p\n",character,&character);
    return 0;
}
display-memory-addresses.c
Copy

Accepting strings

We can tell the computer to accept only a certain number of characters when reading in a string using scanf:

#include <stdio.h>

int main(void){
    char name[40];
    printf("Please enter your name:");
    scanf("%39s",name);

    return 0;
}
accepting-string.c
Copy

We use 39 because the string “name” can only hold 40 characters (39 characters and the string terminator \0).

Notice that when using a string with scanf, we only need to provide the identifier (name) for the string. This is because the name of a string is simply a pointer (reference) to the address of the first character. This helps the computer know where the string begins and the string terminator tells the computer where the string ends.

Support us via BuyMeACoffee