![]() |
VOOZH | about |
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.
sscanf() is used to read formatted input from the string. Both scanf() and sscanf() functions are similar, the only difference between them is that scanf() function reads input from the user from standard input like a keyboard, and sscanf() function reads input from a string and stores the input in another string.
int sscanf ( const char * str, const char * format, ...);
Note: There should be at least as many of these arguments as the number of values stored by the format specifiers.
3 blue balls
This function is specific to Microsoft compilers. It is the same as scanf, except it does not cause buffer overload. scanf_s() function is more secure than scanf() function as it provides an additional parameter to specify the buffer size that can avoid buffer overflow.
int scanf_s(const char *format [argument]...);
Note: Here we can specify the buffer size and actually control the limit of the input so that the whole application don't crash due to memory overflow.
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.
Input 1
Red
Output 1
Red
Input 2
Yellow
Output 2
No Output
Difference between fscanf() and fscanf_s() is same as that of scanf() and scanf_s(). fscanf_s() is secure function that require the size of each c, C, s, S and [ ] type field to be passed as an argument immediately following the variable.
int fscanf_s( FILE *stream, const char *format ,[argument ]... );
Note: fscanf_s has an extra parameter to specify the buffer size and actually control the limit of the input.
Note: fscanf_s will work only in MS Visual studio.
Output
String1 |Hello| String2 |World| String3 |its| Integer |2017|
sscanf_s() is secure function of sscanf() and secure functions require the size of each c, C, s, S and [ type field to be passed as an argument immediately following the variable.
int sscanf_s(const char *restrict buffer, const char *restrict format, ...);
Note: sscanf_s has an extra parameter to specify the buffer size and actually control the limit of the input.
Note: sscanf_s() will only work in Microsoft Visual Studio.
Output
3 blue balls