When the scanf() function reads characters, it will stop reading when it recognizes a space, so how to read a string with spaces?
一、gets()(gets_s())
Reads characters from standard input (stdin) (referred to as keyboard input) and stores them as a C string in str until a newline character or end-of-file is reached.
That is, the gets() function will read characters until it encounters a newline character \n (carriage return) or ends at the end of the file.
It should be noted that the gets() function is replaced by gets_s() in VS.
int main()
{
char str[100] = "\0";
gets_s(str);
puts(str);
return 0;
}
Here you can leave the difference between gets_s() and fgets().
Two, fgets()
From the above figure, we found that fgets() will retain the (\n) carriage return entered in the keyboard when inputting. So I tested it here, and the results are as follows:
Obviously he outputs two newline characters, which is obviously different from my expectation, so I found that the puts() function will also output a (\n) newline character when outputting. If I replace puts() with printf(), then there will be only one fgets() newline character.
Use printf() instead:
3. scanf()
scanf("%[^\n]", str);
scanf can use the above situation to complete the input of strings with spaces.