gets和scanf有什么区别?

如果代码是

scanf("%s\n",message) 

VS

 gets(message) 

有什么区别?似乎他们都得到了消息的输入。

[参考你的特定情况]的基本区别,

  • scanf()在遇到whitespacenewlineEOF时结束输入

  • gets()将空格视为输入字符串的一部分,并在遇到newlineEOF时结束输入。

但是,为避免缓冲区溢出错误并避免安全风险,使用fgets()更安全。

消歧:在以下情况下,如果在正确使用时没有导致麻烦,我会认为“ 安全 ”。 如果“不安全”不能被操纵,那么“不安全”。

 scanf("%s\n",message) 

VS

 gets(message) 

有什么不同?

在安全性方面没有区别,既可以从Standard Input读入也可以很好地溢出message ,如果用户输入更多数据,则message提供内存。

scanf()允许您通过指定要扫描的最大数据量来安全使用:

 char message[42]; ... scanf("%41s", message); /* Only read in one few then the buffer (messega here) provides as one byte is necessary to store the C-"string"'s 0-terminator. */ 

使用gets()无法指定要读入的最大字符数,这就是为什么不使用后者的原因!

有几个。 一个是gets()只会得到字符串数据。 另一个是gets()一次只能得到一个变量。 另一方面,scanf()是一个更灵活的工具。 它可以读取不同数据类型的多个项目。

在您选择的特定示例中,没有太大区别。

主要区别在于读取直到EOF或\n ,而scanf("%s")读取直到遇到任何空格。 scanf还提供了更多格式化选项,但同时它的类型安全性比gets更差。

另一个很大的区别是scanf是一个标准的C函数,而gets已经从语言中删除了,因为它既多余又危险:没有防止缓冲区溢出的保护。 但是,scanf存在同样的安全漏洞,因此在生产代码中不应使用这两个函数

你应该总是使用fgets ,C标准本身甚至推荐这个,见C11 K.3.5.4.1

推荐做法

6 fgets函数允许正确编写的程序安全地处理输入行太长而无法存储在结果数组中。 通常,这要求fgets的调用者注意结果数组中是否存在换行符。 考虑使用fgets (以及基于换行符的任何所需处理)而不是gets_s。

(强调我的)

gets – 从stdin读取字符并将它们存储为字符串。

scanf – 从stdin读取数据并根据scanf语句中指定的格式存储它们,如%d%f%s等。

得到: – >

 gets() reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF, which it replaces with a null byte ('\0'). 

错误: – >

  Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead. 

scanf函数: – >

  The scanf() function reads input from the standard input stream stdin; 

BUG

  Some times scanf makes boundary problems when deals with array and string concepts. 

scanf情况下,你需要提到的格式,不像获取。 所以在你输入charecters,字符串,数字和空格。

对于scanf ,只要遇到空白区域,就会输入结束。

但是在你的例子中你使用的是’%s’,所以, gets()scanf() gets()都不是字符串是指向足够长度的数组的有效指针来保存你发送给它们的字符。 因此很容易导致缓冲区溢出。

提示:使用fgets() ,但这完全取决于用例

scanf不占用空格的概念是完全错误的。 如果你使用这部分代码,它也会占用白色空格:

 #include int main() { char name[25]; printf("Enter your name :\n"); scanf("%[^\n]s",name); printf("%s",name); return 0; } 

使用新线路的地方只会停止输入。 这意味着如果您只按Enter键,它将停止输入。

因此,scanf和gets函数之间基本没有区别。 这只是一种棘手的实施方式。

gets()是不安全的,例如:char str [1]; 得到(str)如果输入的长度超过长度,它将以SIGSEGV结束。 如果只能使用gets,则使用malloc作为基本变量。

scanf()是更灵活的工具,而gets()只获取一个变量。