• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C » Variables » Formatted Input – the scanf Function
Next →
← Prev

Formatted Input – the scanf Function

By Dinesh Thakur

The scanf standard library function is used to read one or more values from the standard input (keyboard) and assign them to specified variables. A typical call to the scanf function takes the following form:

1
scanf(format_string, &varl , &var2, ... ) ;

where var1, var2, … are the names of variables to which values are to be assigned. Note the address of (&) operator before each variable name1• Thus, we actually specify the memory addresses of variables into which the values are to be read. A beginner often forgets to write the address-of operator.

The format_string is similar to that in the printf function. It specifies the format in which the values should be entered from the keyboard. It usually contains conversion specifications (such as %d, %f, %s, %c, etc.) that determine the interpretation of input values.

For each value being read from the keyboard, the scanf function reads the required number of characters from the input field, converts this value to the internal representation of the corresponding argument variable and stores the converted value in that variable. On success, the scanf function returns the number of fields successfully scanned, converted and stored. This value is usually ignored in a scanf function call.

Besides the conversion specifications, the format string may contain whitespace characters (blanks, tabs or newline characters) which cause the whitespace characters in the input to be ignored until a non-whitespace character is encountered. The format string may also contain non-whitespace characters other than % which cause matching characters to be read (but not stored) from the input.

Using Conversion Specifications

A conversion specification in a scanf function call determines how the next input field will be interpreted. In its simplest form, a conversion specification consists of the character % followed by a conversion character. The commonly used conversion characters are given in Table along with the type of argument and the input data expected.

 Table:  The commonly used conversion characters for the scent function

characters

Argument type

Argument converted to

d

int

Decimal integer

f

float

Floating point number (in decimal or scientific notation)

c

char

Character(s)

s

char

String of non-whitespace characters (i. e., a sequence of characters until a newline, tab or space is encountered)

The %d and %f conversion specifications are used to read values for integer and floating point variables, respectively. The %s specification is used to read a string of non-whitespace characters. Whereas, the %c specification is used to read one or more characters that may include whitespace characters. Note that these conversion characters are similar to those used in the printf function.

When using the %d conversion specification, the input should be in the format [±]ddd, i. e., a sequence of digits optionally preceded by a ‘+’ or ‘ – ‘ sign. Similarly, when using the % f conversion specification, the input should be a floating-point number either in decimal or scientific notation. More specifically, the input should be in the format [±]dd[.]dddd[E|e[±]dd] (without any spaces in between), where the fields in square brackets are optional. Note that an integer value is also accepted for the %f specification. The reading of input stops when a whitespace or any character other than those in the specified format is encountered. The unread characters in the input stream are used for subsequent conversion specifications or scanf statements.

Example Reading input from the keyboard

a) Reading numeric data

Consider the statements given below:

1
2
3
int i;
float x;
scanf ("%d%f", &i, &x);

Here, the scanf statement reads values for two variables, i of type int and x of type float, using the %d and %f conversion specifications, respectively. The numbers entered from the keyboard should be separated by whitespace i. e. spaces, tabs or newlines:

100 12.5

Note that the data entered from the keyboard is shown with an underline. Also note that as the Whites pace in the format string causes the whitespace in the input to be ignored, the above scanf statement may be written in a more readable form as shown below.

1
scanf("%d%f", &i, &x);

b) Reading character data

Consider another example given below.

1
2
char a, b, c;
scanf ("%c%c%c", &a, &b, &c);

The scan f statement reads the values for three variables a, b and c of type char. If we wish to assign the characters ‘B’ ‘A’ and ‘T’ to these variables, these characters should be entered from the keyboard, without any whitespace before and between these characters, as follows:

BAT

However, if we enter these characters separated by a single space character as shown below

B A T

the values are assigned to variables as a = ‘B’, b = ‘ ‘ and c = ‘A’ . This is because the %c conversion specifier does not ignore whitespace in the input stream while reading values  from it.

Note that if we wish the scanf statement to correctly read the input containing whitespace (before and between characters), the format string should be modified to include the spaces as shown below:

1
scanf (" %c %c %c", &a, &b, &c);

c) Mixing numeric and character input

Consider the scanf statement given below used to read two integer numbers separated by an operator (such as+,-,*,/, etc.).

1
2
3
int a, b;
char op;
scanf ("%d%c%d", &a, &op, &b);

Now assume that the data is entered as shown below:

10+20

The input for variable a stops when character •+ • is encountered. Thus, value l0 is assigned to variable a. Note that the character ‘+ ‘, which has not yet been read, is assigned to variable op of type char. Subsequently, value 20 is assigned to variable b.

As the user may include spaces while entering the data for this scanf statement, we should include at least one space before the %c specification in the format string as shown below.

1
scanf ("%d %c %d", &a, sop, &b);

d) Reading character strings

Consider the code segment given below.

1
2
3
4
char name[20);
printf("Enter your name: ");
scanf("%s", name);
printf("\nHi %s! Welcome to the wonderful world of C.", name);

Here, name is an array of type char that is used to store the name entered from the keyboard. As one character will be required for the null terminator, the name entered can have at most 19 characters in it. Observe that the address-of operator is not required before array name as the array name itself is a pointer to the first element, i. e., a [0]. A scanf statement is used to read the user’s name from the keyboard. This name is then printed using the printf statement along with a message. The output is shown below.

1
2
Enter your name: Dinesh
Hi Dinesh! Welcome to the wonderful world of C.

e) Reading input in specific format

Consider that we have to read a date in the dd/mm/yyyy format. For this, we can include ‘/’ characters in  the format string as shown below .

1
2
int dd, mm, yy;
scanf("%d/%d/%d",&dd, &mm, &yy);

This scanf statement expects the user to enter three integer values separated by the’/’ character, which is the desired format for the date. Another example where this feature is useful is entering the value of a complex number. The scanf statement given below reads a complex number in the format re+ i im where re and im are the real and imaginary parts, respectively.

1
2
float re, im;
scanf ("%f +i %f", &re, &im);

Note that the space before +i is required to accept the data containing whitespace.

Prompting Users for Data Entry

When a scanf statement is executed, the computer waits for user input. However, the number of input values, their types and the sequence in which these values are expected is not known to the user/operator. Thus, the user is likely to make mistakes while entering the data. To avoid such mistakes, it is a good programming practice to display a message prompt before reading the input as illustrated below.

1
2
printf("Enter deposit, rate and years: ");
scarif ("%f %f %d", &deposit, &rate, &years);

When program containing these statements is executed, a message requesting data from the user is displayed before accepting the data as shown below:

1
Enter deposit, rate and years: 10000 10 5

You’ll also like:

  1. Formatted Output – the printf Function
  2. How to Formatted Output using the printf Function
  3. Function of printf and scanf in C
  4. Write A C++ Program To Add, Subtract And Multiply Two Numbers By Using The Function Within Function Concept (Nesting Of Function).
  5. Input Output Statements in c++
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

C Programming

C Programming Tutorials

  • C - History
  • C - Anatomy
  • C - Constants
  • C - Identifiers
  • C - Data Types
  • C - Libraries File
  • C - Header Files
  • C - Basic Language
  • C - Data Types Sizes
  • C - Header Files Importance
  • C - Escape Sequences
  • C - Main() Purpose
  • C - Program Procedure
  • C - Control Statements
  • C - Enumeration Constant
  • C - Add numbers
  • C - Return Statement
  • C - Avoid Goto
  • C - Command Line Arguments
  • C - Switch Case
  • C - Switch Case Limitations
  • C - getchar() and putchar()
  • C - Iteration Statements
  • C - Pass by Value and Reference
  • C - Structures and Unions
  • C - Structure
  • C - Dynamic Memory
  • C - Fgets and Fputs Functions
  • C - Gets() and Puts() Functions
  • C - Armstrong Number
  • C - Storage Classes
  • C - Fibonacci Series
  • C - Precision Setting
  • C - const Parameters

C - Variable & It's Type

  • C - Variables
  • C - Variable Lifetime
  • C - Static Variable
  • C - Register Variable
  • C - Global Variables
  • C - Auto Variables
  • C - Local Variables

C - Operator & Expressions

  • C - Operator
  • C - Boolean Operators
  • C - Bitwise Operator
  • C - Arithmetic Operators
  • C - Modulus Operator
  • C - Ternary Operator
  • C - Expressions
  • C - Arithmetic Expressions

C - Array

  • C - Arrays
  • C - Array Types
  • C - Array Characteristics
  • C - Static Arrays
  • C - Global Arrays
  • C - 3D Arrays
  • C - Dynamic Arrays
  • C - Pointer to 3D Arrays
  • C - Array Elements Hold
  • C - Arrays as Function Parameters
  • C - Accessing Matrix Elements
  • C - File Handling
  • C - Matrix Multiplication
  • C - Dynamic Memory Allocation

C - Searching & Sorting

  • C - Data Structures
  • C - Linear Search
  • C - Bubble Sort
  • C - Merge Sort
  • C - Linked List
  • C - Insertion Sort
  • C - Binary Search
  • C - Selection Sort
  • C - Quick Sort

C - Functions

  • C - Functions
  • C - Functions Advantages
  • C - Void Functions
  • C - Function Call
  • C - Default Return Value
  • C - String functions

C - Pointer

  • C - Pointers
  • C - Type Casting Of Pointers
  • C - Pointer Advantages
  • C - Pointers Initialization
  • C - Vectors and Pointers

C - Differences

  • C - C Vs C++
  • C - Formal Args. Vs Actual Args.
  • C - Keywords Vs Identifiers
  • C - Strings Vs Character Arrays
  • C - Address Vs Dereference Operator
  • C - Goto Vs longjmp
  • C - Declaring Vs Defining Variable
  • C - String Vs Array
  • C - Call by Value Vs Reference
  • C - Structure Vs Union
  • C - For Vs While loops
  • C - Compiler Vs Interpreter

C - Programs

  • C Program Standard Deviation
  • C Program Calculate Tax
  • C Program Sum Series
  • C Program Merge Arrays
  • C Program Euclid’s Algorithm
  • C Program Print Weekdays
  • C Program Sum of Digits
  • C Program Print a list
  • C Program Print Pythagorean
  • C Program Quiz program
  • C Program Display Table
  • C Program Print Comma-Separated
  • C Program Prints Prime Numbers
  • C Program for Print Integer
  • C Program Count Number
  • C Program Print Color Name
  • C Program Print Odd Numbers
  • C Program Calculate area
  • C Program for a Menu
  • C Program Add Two Vectors
  • C Program Array Addresses
  • C Program Division by Zero Error
  • C Program Compare two Dates
  • C Program Tower of Hanoi
  • C Program return 3 Numbers
  • C Program for Prime Numbers
  • C Program for Factorial
  • C Program for Palindrome

Other Links

  • C Programming - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW