Reading Strings in C: scanf, gets, fgets

In C language, you can use either the scanf function or the gets function to read a string.

  1. reads input from the user
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
  1. receives
char str[100];
printf("请输入一个字符串:");
gets(str);

Another option is to safely read strings using the fgets function.

char str[100];
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);

Using the fgets function can prevent buffer overflow issues that may occur with the gets function.

bannerAds