scanf(“%[^\n]s”, str) Vs gets(str) in C with Examples

gets()

  • gets is a more convenient method of reading a string of text containing whitespaces.
  • Unlike scanf(), it does not skip whitespaces.
  • It is used to read the input until it encounters newline.
  • Syntax:



    gets(string);
    where string-it is a string variable
    

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    #include <stdio.h> 
      
    int main()
    {
        char name[50];
        gets(name);
        printf("Entered name: %s", name);
    }

    chevron_right

    
    

    Output:

    Entered name: GFG
    

%[^\n]

  • It is an edit conversion code.
  • The edit conversion code %[^\n] can be used as an alternative of gets.
  • C supports this format specification with scanf() function.
  • This edit conversion code can be used to read a line containing characters like variables and even whitespaces.
  • In general scanf() function with format specification like %s and specification with the field width in the form of %ws can read-only strings till non-whitespace part.
  • It means they cannot be used for reading a text containing more than one word, especially with Whitespaces.
  • Syntax:

    scanf("%[^\n]", variable_name);
    

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    #include <stdio.h> 
      
    int main()
    {
        char name[50];
        scanf("%[^\n]", name);
        printf("Entered name: %s", name);
    }

    chevron_right

    
    

    Output:

    Entered name: GFG
    

Table of difference between gets() and %[^\n]

gets() %[^\n]
gets() is used to read strings %[^\n] is an edit conversion code used to read strings
Unlike scanf(), gets() reads strings even with whitespaces %[^\n] also terminates with a newline character
when it reads a newline character then the gets() function will be terminated %[^\n] also reads strings with whitespaces


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


5


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.