Open In App

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

gets()

%[^\n]

Note: Both gets() & scanf() are does not perform bound checking.

Table of difference and similarities 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 reads strings with whitespaces
when it reads a newline character then the gets() function will be terminated %[^\n] also terminates with a newline character

Example of gets()




#include <stdio.h>
  
int main() {
    char str[100];
     
    printf("Using gets:\n");
    printf("Enter a line of text: ");
    gets(str); // Reads a line of text, including white-space
    printf("You entered (gets): %s\n", str);
    return 0    
  }

Example of %[^\n]




#include <stdio.h>
  
int main() {
  
    char str[100];
    
    printf("Using scanf:\n");
    printf("Enter a line of text: ");
    scanf("%99[^\n]", str); // Reads a line of text, excluding white-space
    // %99 will stop buffer overflow
    printf("You entered (scanf): %s\n", str);
  
    return 0;
}


Article Tags :