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 a new line.
%[^\n]
- It is an edit conversion code.
- The edit conversion code %[^\n] can be used as an alternative to 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 the non-whitespace part.
- It means they cannot be used for reading a text containing more than one word, especially with Whitespaces.
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;
}
Safety Note: Both gets() and scanf() do not check array bounds, making them unsafe to use as they can lead to buffer overflow.#include <stdio.h>
int main() {
char name[10], sname[10];
// Using gets()
gets(name);
printf("%s\n", name);
// Using scanf() with %[^\n]
scanf("%[^\n]", sname);
printf("%s\n", sname);
return 0;
}
INPUT
Geeks for Geeks
Geeks for Geeks
OUTPUT
Geeks for Geeks
Geeks for Geeks
Here, the complete line—including spaces—is read by both gets() and scanf("%[^\n]"), which then print it out. Nevertheless, if the input exceeds the allotted array size, undefined behavior may result from the absence of bound checking.