📜  C语言中scanf()和gets()之间的区别

📅  最后修改于: 2021-05-25 23:07:45             🧑  作者: Mango

scanf()

  • 它用于从标准输入(键盘)读取输入(字符,字符串,数字数据)。
  • 它用于读取输入,直到遇到空格,换行符或文件结尾(EOF)。

例如,请参见以下代码:

// C program to see how scanf()
// stops reading input after whitespaces
  
#include 
int main()
{
    char str[20];
    printf("enter something\n");
    scanf("%s", str);
    printf("you entered: %s\n", str);
  
    return 0;
}

在这里,输入将由用户提供,输出将如下所示:

Input: Geeks for Geeks
Output: Geeks

Input: Computer science
Output: Computer

得到

  • 它用于从标准输入(键盘)读取输入。
  • 它用于读取输入,直到遇到换行符或文件结尾(EOF)。
// C program to show how gets() 
// takes whitespace as a string.
  
#include 
int main()
{
    char str[20];
    printf("enter something\n");
    gets(str);
    printf("you entered : %s\n", str);
    return 0;
}

在这里,输入将由用户提供,如下所示

Input: Geeks for Geeks
Output: Geeks for Geeks

Input: Computer science
Output: Computer science

它们之间的主要区别是:

  1. scanf()读取输入,直到遇到空格,换行符或文件尾(EOF);而gets()读取输入,直到遇到换行符或文件尾(EOF),gets()遇到空白时,它不会停止读取输入,而是将空白作为字符串。
  2. scanf函数可以读取不同数据类型的多个值而获得()将只能得到数据。

差异可以以表格形式显示如下:

scanf() gets()
when scanf() is used to read string input it stops reading when it encounters whitespace, newline or End Of File when gets() is used to read input it stops reading input when it encounters newline or End Of File.
It does not stop reading the input on encountering whitespace as it considers whitespace as a string.
It is used to read input of any datatype It is used only for string input.

如何使用scanf()从用户阅读完整的句子

实际上,我们可以使用scanf()读取整个字符串。例如,我们可以在scanf()中使用%[^ \ n] s来读取整个字符串。

// C program to show how to read
// entire string using scanf()
  
#include 
  
int main()
{
  
    char str[20];
    printf("Enter something\n");
  
    // Here \n indicates that take the input
    // until newline is encountered
    scanf("%[^\n]s", str); 
    printf("%s", str);
    return 0;
}

上面的代码读取字符串,直到遇到换行符为止。

例子:

Input: Geeks for Geeks
Output: Geeks for Geeks

Input: Computer science
Output: Computer science
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。