Why to use scanf_s()?
scanf just reads whatever input is provided from the console. C does not check whether the user input will fit in the variable that you’ve designated. If you have an array called color[3] and you use scanf for the string “Red”, it will work fine but if user enters more than 3 characters scanf starts writing into memory that doesn’t belong to colour array.
C won’t catch this or warn you and it might or might not crash the program, depending on if something tries to access and write on that memory slot that doesn’t belong to color array. This is where scanf_s comes into play. scanf_s checks that the user input will fit in the given memory space.
Note: scanf_s() will only work in Microsoft Visual Studio.
Example 1: C Program to Illustrate sscanf_s Function
C
// C program to illustrate sscanf_s statement // scanf_s() will only work in Microsoft Visual Studio. #include <stdio.h> #include <stdlib.h> int main() { char a[5]; // sizeof(a) is buffer size scanf_s( "%s" , a, sizeof (a)); printf ( "\n%s " , a); return 0; } |
Input 1
Red
Output 1
Red
Input 2
Yellow
Output 2
No Output
Example 2: C Program to Illustrate the relation between buffer size and array size.
C++
// C++ program // consumes the Enter key // (newline character) pressed after input #include <stdio.h> int main() { // example char ch[100000]; printf ( "Enter characters: " ); scanf_s( "%s" , ch, 99999); getchar (); return 0; } |
C
// C program // consumes the Enter key // (newline character) pressed after input #include <stdio.h> int main() { char ch[100000]; printf ( "Enter characters: " ); scanf_s( "%s" , ch, 99999); getchar (); return 0; } |
- If the buffer size is equal to or smaller than the size of the array, then inputting bigger than or equal to the buffer size will lead to loss of data as the excess data will be truncated and the data till buffer size – 1 will be read.
- If the buffer size is bigger than the size of an array, then
- inputting smaller than buffer size will work out but will give an error
- inputting bigger than buffer size will lead to buffer overflow and give the same error.
Inbuilt library functions for user Input | sscanf, scanf_s, fscanf_s, sscanf_s
The C Programming Language provides various Inbuilt Library Functions for User Input. In this article, we will learn about sscanf, scanf_s, fscanf_s, sscanf_s Library Functions in C.
Contact Us