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

📅  最后修改于: 2023-12-03 15:19:59.275000             🧑  作者: Mango

scanf("%[^\n]s", str) vs gets(str) in C with Examples

In C programming language, there are two standard ways to take input from the user for a string data type, using scanf("%[^\n]s", str) and gets(str). Both have their own pros and cons.

scanf("%[^\n]s", str)

scanf("%[^\n]s", str) is a formatted input function that reads input until it encounters a newline character \n or an end-of-file (EOF) marker. It stores the input characters in the character array str. The %[^\n]s format specifier tells scanf to read all characters except a newline character.

Example:

#include <stdio.h>

int main() {
    char str[50];
    printf("Enter your name: ");
    scanf("%[^\n]s", str);
    printf("Hello, %s!\n", str);
    return 0;
}

Output:

Enter your name: John Doe
Hello, John Doe!

Pros:

  • It provides formatted input, which means we can specify a specific format for the input (e.g. %d for integers, %f for floats, etc.).
  • scanf allows us to read multiple variables in a single line of input.

Cons:

  • It leaves the newline character in the input stream, which can cause problems if we subsequently use fgets or gets.
  • It is difficult to handle errors in input using scanf. For example, if we expect an integer but the user enters a string, the program can crash or behave unpredictably.
  • If the input exceeds the size of the character array we have allocated, scanf can cause buffer overflow.
gets(str)

gets(str) is an unformatted input function that reads input until it encounters a newline character \n or an end-of-file (EOF) marker. It stores the input characters in the character array str, including the newline character.

Example:

#include <stdio.h>

int main() {
    char str[50];
    printf("Enter your name: ");
    gets(str);
    printf("Hello, %s!\n", str);
    return 0;
}

Output:

Enter your name: John Doe
Hello, John Doe!

Pros:

  • It is simpler to use than scanf.
  • It allows us to read input with spaces.

Cons:

  • It leaves the newline character in the input stream, which can cause problems if we subsequently use fgets or scanf.
  • It does not provide formatted input, which means we cannot specify a specific format for the input.
  • It does not provide any error checking or handling mechanism, which can cause problems if the input is not what we expect.
  • It can cause buffer overflow if the input exceeds the size of the character array we have allocated.
Conclusion

In summary, scanf("%[^\n]s", str) is best used for formatted input, where you want to specify a specific format for the input, and gets(str) is best used for unformatted input, where you want to read input with spaces. However, both functions have their own drawbacks, so it is important to use them carefully and with caution. In general, it is recommended to use fgets instead of gets and scanf for input in C programming language.