C scanf Function: Getting User Input in the C language
Getting 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:
- Format specifiers.
- Whitespace characters.
- Non-whitespace characters.
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:
- A ‘*’ sign is an optional specifier, which specifies that user input is read from ‘stdin’ but is ignored and not saved.
- ‘Width’ is an optional specifier that indicates the maximum number from total input characters that can be read from ‘stdin’.
- The ‘length_Modifiers’ propery is another optional item and is used to indicate the exact type for the user input such as long ‘l’ for which no explicit conversion letter exists.
- The ‘type_Specifier’ property is a conversion letter used to indicate the actual type of data that is read from ‘stdin’. User input is converted into the provided type of data and assigned to the corresponding variable.
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.
- The letter ‘c’ shows that the converted input is of type ‘char *’. It is used to represent a single character. If the user inputs has a length greater than one, only the first character is read from all of the input.
Code snippet:
char c; scanf ("%c", &c); //Test printf ( "First character is %c \n", c ); //First character is T
- The letter ‘s’ represents an array of ‘char *’. It converts the input to a character array and ignores the characters after the whitespace.
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.
Recommended Articles
Top courses in C# (programming language)
C# (programming language) 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 Business.