(Translated by https://www.hiragana.jp/)
scanf in C - GeeksforGeeks
Open In App

scanf in C

Last Updated : 06 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C programming language, scanf is a function that stands for Scan Formatted String. It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments.

  • It accepts character, string, and numeric data from the user using standard input.
  • scanf also uses format specifiers like printf.

scanf Syntax

The syntax of scanf() in C is similar to the syntax of printf().

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

Here,

  • int is the return type.
  • format is a string that contains the format specifiers(s).
  • “…” indicates that the function accepts a variable number of arguments.

Example format specifiers recognized by scanf:

%d to accept input of integers.

%ld to  accept input of long integers

%lld to accept input of long long integers

%f to accept input of real number.

%c to accept input of character types.

%s to accept input of a string.

To know more about format specifiers, refer to this article – Format Specifiers in C

Example:

int var;
scanf(“%d”, &var);

The scanf will write the value input by the user into the integer variable var.

Return Value of scanf

The scanf in C returns three types of values:

  • >0: The number of values converted and assigned successfully.
  •   0: No value was assigned.
  • <0: Read error encountered or end-of-file(EOF) reached before any assignment was made.

Why &?

While scanning the input, scanf needs to store that input data somewhere. To store this input data, scanf needs to known the memory location of a variable. And here comes the ampersand to rescue.

  • & is also called as address of the operator.
  • For example, &var is the address of var.

Example of scanf

Below is the C program to implement scanf:

C




// C program to implement
// scanf
#include <stdio.h>
 
// Driver code
int main()
{
    int a, b;
   
      printf("Enter first number: ");
      scanf("%d", &a);
   
      printf("Enter second number: ");
      scanf("%d", &b);
   
      printf("A : %d \t B : %d" ,
            a , b);
   
    return 0;
}


Output

Enter first number: 5
Enter second number: 6
A : 5      B : 6

Related Article:


Previous Article
Next Article

Similar Reads

Problem With Using fgets()/gets()/scanf() After scanf() in C
scanf() is a library function in C. It reads standard input from stdin. fgets() is a library function in C. It reads a line from the specified stream and stores it into the string pointed to by the string variable. It only terminates when either: end-of-file is reachedn-1 characters are readthe newline character is read 1) Consider a below simple p
3 min read
Return values of printf() and scanf() in C/C++
What values do the printf() and scanf() functions return ? printf() : It returns total number of Characters Printed, Or negative value if an output error or an encoding error Example 1: The printf() function in the code written below returns 6. As 'CODING' contains 6 characters. C/C++ Code // C/C++ program to demonstrate return value // of printf()
2 min read
Use of & in scanf() but not in printf()
Why there is need of using '&' in case of scanf function while not in case of printf function. Examples: scanf("%d %d", &a, &b);printf("%d %d", a, b);As a and b above are two variable and each has their own address assigned but instead of a and b, we send the address of a and b respectively. The reason is, scanf() needs to modify values
1 min read
Difference between scanf() and gets() in C
scanf()It is used to read the input(character, string, numeric data) from the standard input(keyboard).It is used to read the input until it encounters a whitespace, newline or End Of File(EOF). For example see the following code: C/C++ Code // C program to see how scanf() // stops reading input after whitespaces #include &lt;stdio.h&gt; in
3 min read
How to Create Your Own scanf() in C?
The scanf() function is used to take input from the console. It is defined in <stdio.h> header file and takes const char* and variable argument list as parameters. In this article, we will learn how to implement your own custom scanf() function in C language. For this, we need to have a firm grasp of the following concepts: Prerequisites: Var
3 min read
Cin-Cout vs Scanf-Printf
Regular competitive programmers face common challenge when input is large and the task of reading such an input from stdin might prove to be a bottleneck. Such problem is accompanied with “Warning: large I/O data”. Let us create a dummy input file containing a line with 16 bytes followed by a newline and having 1000000 such lines, making a file of
3 min read
Why "&" is not used for strings in scanf() function?
Below is syntax of Scanf. It requires two arguments: scanf("Format Specifier", Variable Address); Format Specifier: Type of value to expect while input Variable Address: &variable returns the variable's memory address. In case of a string (character array), the variable itself points to the first element of the array in question. Thus, there is
2 min read
scanf() and fscanf() in C
In C language, scanf() function is used to read formatted input from stdin. It returns the whole number of characters written in it otherwise, returns a negative value. Syntax: int scanf(const char *characters_set)Time Complexity: O(n) Auxiliary Space: O(n) where n is the length of input. Many of us know the traditional uses of scanf. Well, here ar
4 min read
scanf("%[^\n]s", str) Vs gets(str) in C with Examples
gets()gets is a more convenient method of reading a string of text containing whitespaces.Unlike scanf(), it does not skip whitespaces.It is used to read the input until it encounters a new line.%[^\n]It is an edit conversion code.The edit conversion code %[^\n] can be used as an alternative to gets.C supports this format specification with scanf()
2 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
printf in C
In C language, printf() function is used to print formatted output to the standard output stdout (which is generally the console screen). The printf function is a part of the C standard library <stdio.h> and it can allow formatting the output in numerous ways. Syntax of printfprintf ( "formatted_string", arguments_list);Parametersformatted_st
5 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
8 min read
Structure of the C Program
The basic structure of a C program is divided into 6 parts which makes it easy to read, modify, document, and understand in a particular format. C program must follow the below-mentioned outline in order to successfully compile and execute. Debugging is easier in a well-structured C program. Sections of the C ProgramThere are 6 basic sections respo
5 min read
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). Switch case statements follow a selection-control mechanism and allow a value to change control of
8 min read
C Programming Interview Questions (2024)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the old and most popular programming languages. There are many applications in which C programming language is used, including language compilers, operating systems,
15+ min read
scanf in C
In C programming language, scanf is a function that stands for Scan Formatted String. It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments. It accepts character, string, and numeric data from the user using standard input.scanf also uses format specifiers like printf.sc
2 min read
C Hello World Program
The “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. To print the "Hello World", we can use the printf function from the stdio.h library that prints the given string on the screen. C Program to Print "Hello World"The following C program displays "Hello World" in
2 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
Prime Number Program in C
A prime number is a natural number greater than 1 and is completely divisible only by 1 and itself. In this article, we will learn how to check whether the given number is a prime number or not in C. Examples Input: N = 29Output: YesExplanation: 29 has no divisors other than 1 and 29 itself. Hence, it is a prime number. Input: N = 15Output: NoExpla
3 min read
Format Specifiers in C
The format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations. They always start with a % symbol and are used in the formatted string in functions like printf(), scanf, sprintf(), etc. The C language provides a number of format specifiers that are associated with the different
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is <string>. The substring function takes two values pos and len as an argument
8 min read
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. C String Declaration SyntaxDeclaring a string in C is as simple as declaring a one-
8 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
Article Tags :