Another hundred million small details: how to make scanf read strings with spaces like gets

When reading a string in C language, you can use scanf to read a string, and you can also use gets to read a string. What is the difference between the two? Or who should I use when?
Let this article help you sort out their relationship!

The principle of scanf function and gets function to read strings

scanf

The function prototype of scanf: int scanf( const char *format [,argument]... );

When using the scanf function to accept data (including character strings)**, the default setting stops reading when a space enters the tab key (tab key), and at the same time changes the corresponding space enter or tab key to'\0 'To end a string**
That is to say, we can't read a string like "I AM A SUPERMAN" completely, we can only read a string like "IAMASUPERMAN".

gets

The function prototype of gets: char *gets( char *buffer );
The principle of fets is to read a string from the stdin standard input stream and place it in the array buffer. When it encounters a newline character or EOF, it stops reading, and then Change the newline character to'\0' to end a string . Therefore, the function gets does not calculate the size of the string you want to read. You need to set the size of the array in advance to prevent the array from going out of bounds.

Modify the default end flag of scanf to read strings with spaces

So in some OJ online programming, sometimes the gets function is not available, so how do we solve it?
We can use the following statement to modify the end flag of scanf


	char arr[30];
	scanf("%[^\n]",arr);
	puts(arr);

Note: The \n here can be modified to other characters. If it is changed to the character a, then scanf will stop reading when it reads a, and modify a to \0 to end a string.

Guess you like

Origin blog.csdn.net/weixin_51306225/article/details/115315469