Skip to content
Related Articles
Open in App
Not now

Related Articles

Inbuilt library functions for user Input | scanf, fscanf, sscanf, scanf_s, fscanf_s, sscanf_s

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 20 Jan, 2020
Improve Article
Save Article
  1. scanf() : The C library function int scanf (const char *format, …) reads formatted input from stdin.
    Syntax:
    int scanf(const char *format, ...)
    
    Return type: Integer
    
    Parameters:
    format: string that contains the type specifier(s) 
    "..." (ellipsis): indicates that the function accepts
    a variable number of arguments

    Each argument must be a memory address where the converted result is written to. On success, the function returns the number of variables filled. In case of an input failure, before any data could be successfully read, EOF is returned.
    Type specifiers that can be used in scanf:

    %c — Character
    %d — Signed integer
    %f — Floating point
    %s — String




    //C program t illustrate scanf statement
    #include <stdio.h>
    #include <stdlib.h>
      
    int main()
    {
        char a[10]; 
        printf("Please enter your name : \n"); 
          
        //scanf statement
        scanf("%s", a);
      
        printf("You entered: \n%s", a);
      
       return 0;
    }

    Input:

    Geek

    Output:

    Please enter your name : 
    You entered: 
    Geek
  2. sscanf(): sscanf() is used to read formatted input from the string.
    Syntax:
    int sscanf ( const char * s, const char * format, ...);
    
    Return type: Integer
    
    Parameters:
    s: string used to retrieve data
    format: string that contains the type specifier(s)
    … : arguments contains pointers to allocate 
    storage with appropriate type. 
    
    There should be at least as many of these arguments as the 
    number of values stored by the format specifiers.

    On success, the function returns the number of variables filled. In the case of an input failure, before any data could be successfully read, EOF is returned.




    // C program to illustrate sscanf statement
    #include <stdio.h>
      
    int main ()
    {
        // declaring array s
        char s [] = "3 red balls 2 blue balls"
        char str [10],str2 [10];
        int i;
          
        // %*s is used to skip a word
        sscanf (s,"%d %*s %*s %*s %s %s", &i, str, str2);
          
        printf ("%d %s %s \n", i, str, str2);
          
        return 0;
    }

    Output:

    3 blue balls
  3. fscanf(): fscanf() reads formatted data from file and stores it into variables.
    Syntax:
    int fscanf(FILE *stream, const char *format, ...)
    
    Parameters:
    Stream:  pointer to the File object that identifies the stream.
    format : is a string that contains the type specifier(s)
    

    On success, the function returns the number of variables filled. In the case of an input failure, before any data could be successfully read, EOF is returned.




    // C program to illustrate sscanf statement
    // This program will run on system having the file file.txt
    #include <stdio.h>
    #include <stdlib.h>
      
    int main()
    {
        char s1[10], s2[10], s3[10];
        int year;
          
        // file pointer
        FILE * fp; 
          
        // opening/creation of file
        fp = fopen ("file.txt", "w+");     
          
        // storing string in the file
        fputs("Hello World its 2017", fp); 
          
        // sets the file position to the beginning of the file
        rewind(fp); 
          
        // taking input from file
        fscanf(fp, "%s %s %s %d", s1, s2, s3, &year); 
          
        printf("String1 |%s|\n", s1 );
        printf("String2 |%s|\n", s2 );
        printf("String3 |%s|\n", s3 );
        printf("Integer |%d|\n", year );
          
        // close file pointer
        fclose(fp);     
          
        return(0);
    }

    Output:

    String1 |Hello|
    String2 |World|
    String3 |its|
    Integer |2017|
    
  4. scanf_s() : This function is specific to Microsoft compilers. It is the same as scanf, except it does not cause buffer overload.
    Syntax:
    int scanf_s(const char *format [argument]...);
    
    argument(parameter): here you can specify the buffer size and actually control the limit
    of the input so you don't crash the whole application.

    On success, the function returns the number of variables filled. In the case of an input failure, before any data could be successfully read, EOF is returned.
    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 “Red”, it will work fine but if user enters more than 3 characters scanf starts writing into memory that doesn’t belong to colour. 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. This is where scanf_s comes into play. scanf_s checks that the user input will fit in the given memory space.




    // 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:

    Red

    Output:

    Red

    Input:

    Yellow

    Output:

    No Output

    Illustrating the relation between buffer size and array size.

    C




    // C program
    // consumes the Enter key 
    // (newline character) pressed after input
    #include<stdio.h>
      
    char ch[100000];
    printf("Enter characters: ");
    scanf_s("%s", ch, 99999);
    getchar();

    C++




    // C++ program
    // consumes the Enter key 
    // (newline character) pressed after input
      
    #include "stdafx.h"
      
    int _tmain(int argc, _TCHAR* argv[])
    {
        // example
        char ch[100000];
        printf("Enter characters: ");
        scanf_s("%s", ch, 99999);
        getchar();
        return 0;
    }

    1. 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 do nothing.
    2. If the buffer size is bigger than the size of an array, then
      1. inputting smaller than buffer size will work out but will give an error

        “Run-Time Check Failure #2 – Stack around the variable ‘variable_name’ was corrupted.”

      2. inputting bigger than buffer size will do nothing and give the same error.
  5. fscanf_s() : Difference between fscanf() and fscanf_s() is same as that of scanf() and scanf_s(). fscanf_s() is secure function 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.
    Syntax:
    int fscanf_s(   FILE *stream,  const char *format ,[argument ]... ); 
    
    fscanf_s has an extra argument(parameter) where you can 
    specify the buffer size and actually control the limit of the input.
    

    On success, the function returns the number of variables filled. In the case of an input failure, before any data could be successfully read, EOF is returned.




    //C program to illustrate fscanf_s statement
    //This program will run on MS Visual studio
    #include <stdio.h>
    #include <stdlib.h>
      
    int main()
    {
        char s1[10], s2[10], s3[10];
        int year;
          
        // file pointer
        FILE * fp; 
      
        // Open file securely
        fopen_s(&fp,"file.txt", "w+"); 
          
        fputs("Hello World its 2017", fp); 
      
        rewind(fp);
      
        // Using fscanf_s
        fscanf_s(fp, "%s", s1, sizeof(s1));
        fscanf_s(fp, "%s", s2, sizeof(s2));
        fscanf_s(fp, "%s", s3, sizeof(s3));
        fscanf_s(fp, "%d", &year, sizeof(year));
      
        printf("String1 |%s|\n", s1);
        printf("String2 |%s|\n", s2);
        printf("String3 |%s|\n", s3);
        printf("Integer |%d|\n", year);
      
        fclose(fp);
      
        return(0);
    }

    Output:

    String1 |Hello|
    String2 |World|
    String3 |its|
    Integer |2017|
    
  6. sscanf_s() : 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.
    Syntax:
    int sscanf_s(const char *restrict buffer, const char *restrict format, ...);
    
    sscanf_s has an extra argument(parameter) where you can specify 
    the buffer size and actually control the limit of the input.
    

    On success, the function returns the number of variables filled. In the case of an input failure, before any data could be successfully read, EOF is returned.




    //C program to illustrate sscanf_s statement
    //This program will run on MS Visual studio
    #include <stdio.h>
      
    int main()
    {
        char s[] = "3 red balls 2 blue balls";
        char str[10], str2[10];
        int i;
      
        // %*s is used to skip a word
        sscanf_s(s, "%d", &i, sizeof(i));
        sscanf_s(s, "%*d %*s %*s %*s %s", str, sizeof(str));
        sscanf_s(s, "%*d %*s %*s %*s %*s %s", str2, sizeof(str2));
          
        printf("%d %s %s \n", i, str, str2);
      
        return 0;
    }

    Output:

    3 blue balls 
    

    Note: sscanf_s() will only work in Microsoft Visual Studio.

This article is contributed by Kartik Ahuja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!