Programming in C: User Input

In the previous tutorial we took a look at modifiers in C, today we will look at how to deal with user input. User input is one of the most valuable parts of programming in any language. There are many ways that we can get user input in C, but this tutorial will focus on using the scanf function.

The scanf function allows you as a programmer to tell the computer to wait for user input (normally entered using a keyboard), and then storing the value entered by the user in a variable. Here is the general form of the scanf function:

scanf("format_string", &variable_name); 

The format in the double quotes is the same format string used in printf, as seen the C tutorial about variables and using the printf function. The variable name followed by the ampersand is the variable in which the value entered by the user will be stored. 

The ampersand before the variable name tells the program to put the value entered by the user into the memory location the variable points to, essentially it takes the variable and set it to the value entered by the user.

Here is an example of a simple program using scanf:

#include <stdio.h>
int main(void)
{
char first_initial, last_initial;
intage;
printf("Enter first and last initial and your age (separated by a space):");
scanf("%c %c %d", &first_initial, &last_initial, &age);

printf("\nHello %c%c. Your age is %d\n", first_initial, last_initial, age);
return 0;
}

More tutorials coming soon! Let me know how you like the tutorials by commenting below and if there is any specific topics or languages you would like covered.

Introduction to Bash Shell Scripting: Linux Commands - Part 2

Google Acquires Nest Labs for $3.2 Billion