Both the scanf () function and the Get () function are available for input strings, but are functionally different. If you want to enter the string "Hi Hello" from the keyboard, you should use the __gets__ function.
The get can receive spaces, and scanf encounters a space, carriage return, and TAB key will assume that the input ends, and that it cannot receive spaces.
Char string[15]; Gets (string); /* Encountered a carriage return that the input ended */
scanf ("%s", string); /* Encountered a space thought input ended */
So when you include spaces in the string you enter, you should use the gets input.
scanf and gets the difference when getting a string
In the C language, there are at least two functions that can get a string:
1.SCANF ()
Header file: stdio.h
Syntax: scanf ("Format control string", variable address list);
When string is accepted: scanf ("%s", character array name or pointer);
2.gets ()
Header file: stdio.h
Syntax: Gets (character array name or pointer);
Both when accepting a string:
1. Different points:
SCANF cannot accept space, Tab tab, carriage return, etc.;
And get can accept space, Tab tab and enter, etc.;
2. The same point:
The string is automatically added after the end of the acceptance.
Example 1:
#include <stdio.h>
Main ()
{
Char ch1[10],ch2[10];
scanf ("%s", CH1);
Gets (CH2);
}
Type ASD space FG carriage return, ASD space FG Enter, then ch1= "asd\0", ch2= "ASD fg\0".
Example 2:
#include <stdio.h>
Main ()
{
Char ch1[10],ch2[10],c1,c2;
scanf ("%s", CH1);
C1=getchar ();
Gets (CH2);
C2=getchar ();
}
Type ASDFG carriage return, ASDFG Enter, then ch1= "Asdfg\0", c1= ' \ n ', ch2= "Asdfg\0", C2 needs to be entered.
SCANF: When a carriage return is encountered, the Space and tab keys are automatically added after the string, but the carriage return, the Space and tab keys remain in the input buffer.
Get: Can accept all the characters entered before the Enter key, and use ' \ n ' instead of '/'. Enter will not be left in the input buffer
Gets () used to read the string, end the input with a carriage return
SCANF () can read all types of variables
////////////////////////////////////
Using the get under Linux gcc warning: Because the gets function does not limit the length of the string when it is entered.
You can use the fgets () function instead, as follows:
Char String[lenth];
Gets (string); = = Change to ==>fgets (String,length,stdin);
This makes it possible to use fgets as a perfect substitute for get, and also to help us check for a mistake.
scanf gets fgets difference and contact