C Input

In this lesson, you will learn how to take user input using the scanf() function and an example to understand the topic better.

C scanf() Function

The scanf() function takes two arguments:

  • The First argument is the format specifier of the variable (%s in the example below)
  • The Second argument is the reference operator (&sub_name). The reference operator stores the memory address of the variable.

Example of scanf()

//program takes the input subject name using scanf function and display subject name using printf.
#include <stdio.h>
int main() {
  char sub_name[100];
  scanf("%s", sub_name); // Takes the string input
  printf("You entered: %s\n", sub_name); // output
  return 0;
}

Output

Learnmodo
You entered: Learnmodo

scanf() Format Specifiers

scanf() format specifiers tell the compiler what to expect from the user as a data type. The example above uses the %s specifier, which is used to scan an entire string.

Below are the most used specifiers in C

Format Specifier Data type
%c A character. Example: ‘A’
%s A entire string. Example: Learnmodo
%hi signed short
%hu unsigned short. Example: +399
%Lf long double.
%d Base 10 decimal integer
%i Decimal integer. It detects the base automatically
%o A base 8 octal integer
%x A base 16 hexadecimal integer
%p A memory Address (pointer)
%f A float number
%u unsigned decimal
%e or %E Scientific notation Of a floating point number
Note
you will learn in detail about datatype later in this course

The next lesson will teach you C Comments and how to use them in your code.