How to obtain a string in C language?

In the C language, there are several ways to obtain strings.

  1. “By using a character array, you can declare a character array to store a string and use the scanf() function to get the user’s input. For example: “
#include <stdio.h>

int main() {
   char str[100];

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

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

   return 0;
}
  1. Using a pointer: you can declare a character pointer to store a string and use the gets() function to receive the input string from the user. For example:
#include <stdio.h>

int main() {
   char *str;

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

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

   return 0;
}

It is important to note that when using pointers to retrieve strings, you must allocate memory space for the pointer beforehand or use dynamic memory allocation functions like malloc() to allocate memory space for the pointer.

Furthermore, if you need to obtain strings with spaces, it is suggested to use the fgets() function instead of scanf() or gets() to prevent potential input overflow issues.

bannerAds