How to read strings in the C language?

In the C language, you can use the scanf function or the gets function to read strings.

  1. Read input from standard input.
char str[100];
scanf("%s", str);

However, one issue with this method is that it can only read the string before the space, so it can only read the part before the space if there are spaces in the input string.

  1. obtains
char str[100];
gets(str);

This method can read strings containing spaces, but the gets function has security issues because it cannot determine the length of the input string and does not provide protection against buffer overflow.

To avoid the safety issues of the gets function, it is recommended to use the fgets function instead, which allows you to specify the maximum number of characters to read.

char str[100];
fgets(str, sizeof(str), stdin);

This can help avoid buffer overflow issues and also allow for reading strings with spaces.

bannerAds