Method for inputting strings in the C language

In C language, you can use the scanf and gets functions to input strings.

  1. scanf is used in C programming language for taking input from standard input (keyboard).
#include <stdio.h>

int main() {
   char str[100];

   printf("请输入字符串:");
   scanf("%s", str);

   printf("您输入的字符串是:%s\n", str);

   return 0;
}

In the above code, scanf(“%s”, str) is used to input a string and store it in the character array str.

  1. receives
#include <stdio.h>

int main() {
   char str[100];

   printf("请输入字符串:");
   gets(str);

   printf("您输入的字符串是:%s\n", str);

   return 0;
}

The code above uses gets(str) to input a string and store it in the character array str.

It should be noted that the gets function has security issues and is not recommended for use in practical development. Instead, consider using the fgets function, which allows you to specify the maximum number of input characters in order to avoid buffer overflow.

#include <stdio.h>

int main() {
   char str[100];

   printf("请输入字符串:");
   fgets(str, sizeof(str), stdin);

   printf("您输入的字符串是:%s\n", str);

   return 0;
}

The fgets(str, sizeof(str), stdin) in the code above is used to input a string and store it in the character array str. The sizeof(str) indicates the maximum number of characters that can be input, and stdin represents standard input.

bannerAds