Difference between C-language gets () and scanf () Functions
Both scanf () and gets () functions can be used to input strings, but they differ in functionality. To input the string "hi hello" on the keyboard, use the _ gets _ function. Gets can receive spaces, while scanf can receive spaces when it encounters spaces, press enter, and Tab keys. Char string [15]; gets (string);/* The input ends when the carriage return occurs */scanf ("% s", string ); /* when a space is used to indicate that the input is over */Therefore, when the input string contains spaces, use gets for the input. The difference between scanf and gets when obtaining a string is in C language. There are at least two functions that can construct a string: 1. the header file of scanf (): stdio. h Syntax: scanf ("format control string", variable address list); when receiving string: scanf ("% s", character array name or pointer); 2. header file of gets (): stdio. h Syntax: gets (character array name or pointer); when receiving strings: 1. differences: scanf cannot accept spaces, Tab tabs, and carriage return. gets can accept spaces, Tab tabs, and carriage return. 2. similarities: After the string is accepted, '\ 0' is automatically added '. Example 1: # include <stdio. h> main () {char character [10], ch2 [10]; scanf ("% s", character); gets (ch2);} type asd space fg in sequence and press Enter, press ENTER for asd space fg, and then fill = "asd \ 0", ch2 = "asd fg \ 0 ". Example 2: # include <stdio. h> main () {char character [10], ch2 [10], c1, c2; scanf ("% s", clerk); c1 = getchar (); gets (ch2); c2 = getchar ();} press asdfg and asdfg, then press = "asdfg \ 0", c1 = '\ n ', ch2 = "asdfg \ 0", c2 is required. Scanf: When you press enter, the space and tab keys will automatically add '\ 0' to the end of the string, but the press enter, space, and tab keys will remain in the input buffer. Gets: accepts all characters entered before the Enter key and replaces '\ 0' with' \ n '. the enter key does not remain in the input buffer. gets () uses the read string and ends the input scanf () to read all types of variables.