C - scanf() function

Introduction

scanf() is the input version of the printf() function.

Here's the format:

#include <stdio.h> 

int scanf(const char *restrict format,...); 

Here's a simple version of the format:

scanf("placeholder ",variable); 

In this code, placeholder is a conversion character, and variable is a type of variable that matches the conversion character.

Unless it's a string (char array), the variable is prefixed by the & operator.

Here are some scanf() examples:

To read an integer value into the variable highscore.

scanf("%d",&highscore); 

To read a floating-point value to be input, which is then stored in the temperature variable.

scanf("%f",&temperature); 

To read character input and store it in the key variable.

scanf("%c",&key); 

The %s placeholder is used to read in text, but only until the first white space character is encountered.

So a space or a tab or the Enter key terminates the string. firstname is a char array, so it doesn't need the & operator in the scanf() function.

scanf("%s",firstname); 

Related Topics

Exercise