In C language, scanf() and gets() are both used to read input from the standard input (keyboard), so what are the differences between them? This article will briefly compare scanf() and gets(), and introduce the differences between scanf() and gets(). I hope it will be helpful to you. [Video tutorial recommendation: C Language Tutorial]
##scanf() function# The ##scanf() function is used to read data (characters, strings, numbers) entered from the keyboard; it will stop reading data when it encounters a space, newline character or end of file (EOF).
Code example:
#include <stdio.h> int main() { char str[20]; printf("请输入:\n"); scanf("%s", str); printf("输出: %s\n", str); return 0; }
Output:
##gets() functiongets() function is also used to read data input from the keyboard and obtain strings. Will stop reading data when encountering a newline character or end-of-file (EOF).
Code example:#include <stdio.h> int main() { char str[20]; printf("请输入:\n"); gets(str); printf("输出: %s\n", str); return 0; }
##Difference between scanf() and gets()
1. When the scanf() function is reading input, it will stop reading when it encounters a space, newline character or end of file. However, when reading input, the gets() function will stop reading when it encounters a newline character or the end of the file; it will treat a space as a character in the string, so it will not stop reading when it encounters a space. enter. 2. The scanf() function is used to read multiple values of different data types; while the gets() function can only obtain string data.
The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of Difference between scanf() and gets() in C. For more information, please follow other related articles on the PHP Chinese website!