📜  C中scanf()和gets()的区别

📅  最后修改于: 2021-09-13 02:58:44             🧑  作者: Mango

扫描()

  • 它用于从标准输入(键盘)读取输入(字符、字符串、数字数据)。
  • 它用于读取输入,直到遇到空格、换行符或文件结尾 (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 基础课程