C language string functions puts() and gets()

Article directory

puts()

Belongs to the standard library <stdio.h>

Function prototype:

int puts(const char *str)

str - This is the C string to be written.

The function returns a non-negative value for the length of the string (including the trailing \0) on success, or EOF if an error occurs.

Function: The puts() function only displays the string, writes a string to the standard output stdout, until the null character, but not including the null character. A newline is automatically added at the end of the line.

Give the address of a character to the puts() function, and it will output characters backward until it encounters a null character, and will not output a null character, and automatically add a newline character.

Program example:

#include<stdio.h>

int main(void)
{
    
    
	char str1[] = "hello";
	puts(str1);
	puts(str1);

	return 0;
}

result:

hello
hello

It can be seen that the line is automatically changed.

gets()

Belongs to the standard library <stdio.h>

Function prototype:

char *gets(char *str);

There is only one parameter. The parameter type is char*, that is, str can be a character pointer variable name, or a character array name.

The function of the gets() function is to read a character string from the input buffer and store it in the memory space pointed to by the character pointer variable str.

The gets() function reads an entire line of input until it encounters a newline character, then discards the newline character, stores the remaining characters, and appends a null character at the end of these characters to make it a C string.

gets() is often paired with puts(). puts() is used to display strings, and automatically adds line breaks.

Program example:

#include<stdio.h>

int main(void)
{
    
    
	char ch[20] = {
    
     '\0' };
	printf("请输入字符串:");
	gets(ch);
	puts(ch);

	return 0;
}

result:

请输入字符串:i love you!
i love you!

The unsafe place of the gets() function: there is only one parameter, that is, the location where the read-in string should be placed in memory, and it is not known whether this location can hold so much content you read in.

Guess you like

Origin blog.csdn.net/chengkai730/article/details/132393373