Trusted answers to developer questions

How to read data using scanf() in C

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

In C, the scanf() function is used to read formatted data from the console.

svg viewer

Syntax

The general syntax of scanf is as follows:

int scanf(const char *format, Object *arg(s))

Parameters

  • Object: Address of the variable(s) which will store data

  • char *: This contains the format specifiers

Format Specifier

Format specifier is a special character which is used to specify the data type of the value being read.

Some of the frequently used specifiers are as follows:

  • s - strings
  • d – decimal integers
  • f – floating-point numbers
  • c – a single character

Return value

  • If the function successfully reads the data, the number of items read is returned

  • In case of unsuccessful execution, a negative number is returned

  • If there is an input failure, EOF is returned


Code

1. Reading an integer and a floating point value

#include <stdio.h>
int main()
{
int a;
float b;
int x = scanf("%d%f", &a, &b);
printf("Decimal Number is : %d\n",a);
printf("Floating-Point Number is : %f\n",b);
printf("Return Value: %d",x);
return 0;
}

Enter the input below

Note:

  • To use the scanf() function, the stdio.h library must be included

  • The scanf() function requires the address of the variable, not the actual variable itself. This is done to store the value at the memory location of the variable.

2. Reading a string

#include <stdio.h>
int main()
{
char name[20];
scanf("%s", &name);
printf("Your name is: %s", name);
return 0;
}

Enter the input below

Note: In C, a string is the address of the character buffer which is why we do not need & with the variable.

RELATED TAGS

c
formatted input
stdin
input
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?