The c language retrieves user input strings as an elaboration of the differences between scanf and gets

  • 2020-06-07 04:56:50
  • OfStack

explain

gets(s) function and scanf("%s", & s) similar but not identical, using scanf("%s", & The problem with the s) function is that if a space is entered, the string is considered finished and the character after the space is treated as the next entry, but the gets() function receives the entire string until it encounters a newline.

1.scanf()

Header file: stdio. h

Syntax: scanf(" format control string ", variable address list);

scanf("%s", character array name or pointer);

2.gets()

Header file: ES33en.h

Syntax: gets(character array name or pointer);

Both accept strings:

1. Differences:

scanf does not accept Spaces, tabs Tab, carriage return, etc.

gets accepts Spaces, tabs, Tab, carriage returns, etc.

2. Similarities:

The string is automatically added '\0' when it is accepted.

Case 1:


#include <stdio.h>
int main()
{
  char ch1[10],ch2[10];

  scanf("%s",ch1);
  gets(ch2);

return 0;
}

Type asd space fg enter, asd space fg enter, ch1="asd\0", ch2="asd fg\0".

Program 2:


#include <stdio.h>
int main()
{
char str1[20], str2[20];
scanf("%s",str1);
printf("%s\n",str1); 
scanf("%s",str2);
printf("%s\n",str2);
return 0;
}

The function of the program is to read in 1 string output and then read in 1 string output. However, we will find that there is no space in the input string, such as:

Test 1 Input:


Hello word(enter)

Output:


Hello
world!

Application:


#include <stdio.h>
int main()
{
char str1[20], str2[20];
gets(str1);
printf("%s\n",str1); 
gets(str2);
printf("%s\n",str2);
return 0;
}

Testing:


Helloworld! [ The input ]
Helloworld! [ The output ]
12345 [ The input ]
12345 [ The output ]

This time, the program performs two reads from the keyboard, and the first string takes Helloworld! Accepts a space character instead of splitting two strings as in the previous program! Therefore, scanf() is not recommended when reading a blank string.


Related articles: