Udemy logo

c scanfGetting user input is integral to interactive applications such as games, real time systems and other event-driven applications. This input decides the execution of particular functionality of a system. In the C language, any program or application with a command line interface uses the ‘scanf’ method for this purpose.

What is C Scanf Function?

The C ‘scanf’ method is a function located in a ‘stdio’ library. It is used to read a formatted input including a character, string, and numeric data  from Standard Input (stdin), which is generally a keyboard. Though scanf is an extremely useful function in simpler programs, it does not effectively handle human input errors. This makes the C ‘scanf’ function a little unreliable and hence should only be used to implement simple programs where reliability is not a priority.

Want to learn more about C? Check out this course at Udemy.com

C Scanf Function Syntax

#include <stdio.h>
int scanf ( const char *format, &variable, ... );

In order to use C scanf, the library ‘stdio’ is required in the source code file. You can see from the C ‘scanf’ function’s syntax that a user’s input is formatted with a ‘format’ argument. A valid format is assigned to an argument ‘variable’.

The ‘format’ argument of C ‘scanf’ function is a C character string, consisting of one or more of the following components:

On successful execution of the C ‘scanf’ function, the total number of characters read from the input is returned. If it fails, a negative value or an ‘EOF’ is returned by the function.

C Scanf Function Format Specifiers

% [*] [width] [length_Modifiers] type_Specifier

The C ‘scanf’ function format is a combination of the parameters mentioned above. Every specifier is preceded by a percentage (%) sign. A brief description of the aforementioned format specifiers is given below:

New to C language? This course at Udemy.com might help

C Scanf Function Type Specifier

The C ‘scanf’ function type specifiers identify the type of an input. The following are some of the most important and frequently used type specifiers.

Code snippet:

char c;
scanf ("%c", &c); //Test
printf ( "First character is %c \n", c ); //First character is T

Code snippet:

char firstName [50];
scanf ( " %s", firstName); //John Doe
printf ( "Provided name is %s \n", firstName); //John
// Letters ‘d’ and ‘i’ represent a decimal integer.
int i = 0;
scanf ( "%d", &i); //-21
printf ( "Number entered is %d \n", i ); //-21
// Letters ‘a’, ‘e’, ‘f’ and ‘g’ are the input conversion letters for a float and double.
float x;
scanf ( "%f", &x); //21.12
printf ( "You are %f years old.\n", x ); //21.120000
// Letter ‘x’ takes a user input in the form of hexadecimal integer.
unsigned int i = 0;
scanf ( "%x", &i); //A
printf ( "Decimal value is %i \n", i ); //10

C Scanf Function Additional Arguments

Additional arguments in the C ‘scanf’ function depend on numbers of format specifiers in a ‘format’ string since each saves a part of the input. An equal number of format specifiers and variables in a function are recommended or else the function may return ambiguous results. The following code snippet illustrates the usage of multiple format specifiers:

Code snippet:

unsigned int age = 0;  int id;  char name [50];
printf ( "Enter a Name, Age, ID and Security Code \n" );
scanf ( " %[^\n] %2d %i %*d", name, &age, &id );
printf ( "User Name is %s \n", name );
printf ( "Age of %i.\n", age );
printf ( "With an ID = %i.\n", id );
Input Output
John Doe2277999 User Name is John DoeAge of 22.With an ID = 77.

C Scanf Function variant ‘sscanf’

int sscanf (const char *inputStr, const char *format, &variable, … );

C ‘scanf’ and ‘sscanf’ functions are similar in functionality. The only difference between the two is that ‘scanf’ reads input from Standard Input. On the contrary, ‘sscanf’ reads input from a character string, which is passed as the first argument to the function.

C Scanf Function alternative

The C ‘scanf’ function is not able to detect a buffer overflow. Therefore, when a provided buffer reaches its limit, the extra input characters overwrite the memory that might be already occupied.  The following example demonstrates this concept:

char nameWithSpace [5];
scanf ( "%[^\n]", nameWithSpace ); //John Doe
printf ( "Full name is %s \n", nameWithSpace ); //John Doe

In the above code snippet, the buffer size is ‘5’ but user input with a length of more than ‘5’ overflows that buffer. A better alternative exists in the form of  the ‘fgets’ function, which reads a line from a specified stream including Standard Input.

Conclusion

Scanf is one of the most fundamental functions of the C language and is used to perform basic input operations such as getting string input from the user in command line applications. To further study the C language and its core functionality, you can take some of the fundamental C language courses at extremely reasonable price at Udemy.com. One such course can be found here at Udemy.com.

Page Last Updated: June 2014

Top courses in C#

Complete C# Masterclass
Denis Panjuta, Tutorials.eu by Denis Panjuta
4.6 (20,236)
Complete C# Unity Game Developer 3D
Ben Tristem, Rick Davidson, GameDev.tv Team, Gary Pettie
4.7 (34,573)
Bestseller
Unity RPG Inventory Systems Asset Pack: Behind The Scenes
Sam Pattuzzi, GameDev.tv Team, Rick Davidson
4.6 (658)
C#/.NET - 50 Essential Interview Questions (Mid Level)
Krystyna Ślusarczyk
4.9 (42)
Bestseller
Complete C# Unity Game Developer 2D
GameDev.tv Team, Rick Davidson, Gary Pettie
4.7 (94,002)
Learn Parallel Programming with C# and .NET
Dmitri Nesteruk
4.5 (2,797)
Bestseller
RPG Core Combat Creator: Learn Intermediate Unity C# Coding
Ben Tristem, Rick Davidson, Sam Pattuzzi, GameDev.tv Team
4.8 (9,877)
Design Patterns in C# and .NET
Dmitri Nesteruk
4.5 (9,238)
Bestseller
C# 10 | Ultimate Guide - Beginner to Advanced | Master class
Web University by Harsha Vardhan
4.5 (1,135)

More C# Courses

C# students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.

Request a demo