C语言 get 和 scanf 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26602608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:30:35  来源:igfitidea点击:

What's the difference between gets and scanf?

cinputscanfgets

提问by Shihe Zhang

If the code is

如果代码是

scanf("%s\n",message)  

vs

对比

gets(message)

what's the difference?It seems that both of them get input to message.

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

回答by Sourav Ghosh

The basic difference [in reference to your particular scenario],

[参考您的特定场景]的基本区别,

  • scanf()ends taking input upon encountering a whitespace, newlineor EOF

  • gets()considers a whitespace as a part of the input string and ends the input upon encountering newlineor EOF.

  • scanf()遇到 a 时结束接受输入whitespacenewlineEOF

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

However, to avoid buffer overflowerrors and to avoid security risks, its safer to use fgets().

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

回答by alk

Disambiguation: In the following context I'd consider "safe" if not leading to trouble when correctly used. And "unsafe" if the "unsafetyness" cannot be maneuvered around.

消歧义:在以下上下文中,如果正确使用不会导致麻烦,我会认为“安全”。和“不安全”如果“unsafetyness”不能操纵的周围。

scanf("%s\n",message)

vs

gets(message)

What's the difference?

scanf("%s\n",message)

对比

gets(message)

有什么不同?

In terms of safety there is no difference, both read in from Standard Inputand might very well overflow message, if the user enters more data then messageprovides memory for.

在安全性方面没有区别,如果用户输入更多数据然后提供内存,则两者都从读取Standard Input和很可能溢出。messagemessage

Whereas scanf()allows you to be used safely by specifying the maximum amount of data to be scanned in:

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. */

With gets()it is notpossible to specify the maximum number of characters be read in, that's why the latter shall not be used!

有了gets()不是可以指定字符在读的最大数量,这就是为什么后者不得使用

回答by Lundin

The main difference is that getsreads until EOF or \n, while scanf("%s")reads until any whitespace has been encountered. scanfalso provides more formatting options, but at the same time it has worse type safety than gets.

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

Another big difference is that scanfis a standard C function, while getshas been removed from the language, since it was both superfluous and dangerous: there was no protection against buffer overruns. The very same security flaw exists with scanf however, so neither of those two functions should be used in production code.

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

You should always use fgets, the C standard itself even recommends this, see C11 K.3.5.4.1

您应该始终使用fgets,C 标准本身甚至建议这样做,请参阅 C11 K.3.5.4.1

Recommended practice

6 The fgets function allows properly-written programs to safely process input lines too long to store in the result array. In general this requires that callers of fgets pay attention to the presence or absence of a new-line character in the result array. Consider using fgets(along with any needed processing based on new-line characters) instead of gets_s.

推荐做法

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

(emphasis mine)

(强调我的)

回答by Shwetha

gets- Reads characters from stdin and stores them as a string.

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

scanf- Reads data from stdin and stores them according to the format specified int the scanfstatement like %d, %f, %s, etc.

scanf-根据的int指定的格式他们读取从stdin数据并存储scanf等声明%d%f%s等。

回答by Dinesh

There are several. One is that gets() will only get character string data. Another is that gets() will get only one variable at a time. scanf() on the other hand is a much, much more flexible tool. It can read multiple items of different data types.

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

In the particular example you have picked, there is not much of a difference.

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

回答by Anbu.Sankar

gets:->

得到:->

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

gets()从 stdin 读取一行到 指向的缓冲区, s直到终止换行符或 EOF,它用空字节 ( '\0')替换。

BUGS:->

错误:->

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.

永远不要使用gets(). 因为在事先不知道数据的情况下无法知道gets()会读取多少个字符 ,并且因为gets()会继续存储超过缓冲区末尾的字符,所以使用起来极其危险。它已被用来破坏计算机安全。使用fgets()来代替。

scanf:->

扫描:->

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

scanf()函数从标准输入流 stdin 读取输入;

BUG:->

错误:->

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

有时 scanf 在处理数组和字符串概念时会产生边界问题。

回答by argentum47

In case of scanfyou need that format mentioned, unlike in gets. So in getsyou enter charecters, strings, numbers and spaces.

如果scanf您需要提到的格式,与gets 不同。因此,gets您可以输入字符、字符串、数字和空格。

In case of scanf, you input ends as soon as a white-space is encountered.

在 的情况下scanf,一旦遇到空格,您的输入就会结束。

But then in your example you are using '%s' so, neither gets()nor scanf()that the strings are valid pointers to arrays of sufficient length to hold the characters you are sending to them. Hence can easily cause an buffer overflow.

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

Tip: use fgets(), but that all depends on the use case

提示:使用fgets(),但这一切都取决于用例

回答by Kambugu Ismail

scanf()is much more flexible tool while gets()only gets one variable at a time.

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

回答by Anirban Ghosh

The concept that scanf does not take white space is completely wrong. If you use this part of code it will take white white space also :

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

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

Where the use of new line will only stop taking input. That means if you press enter only then it will stop taking inputs.

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

So, there is basically no difference between scanf and gets functions. It is just a tricky way of implementation.

所以,scanf和gets函数基本上没有区别。这只是一种棘手的实现方式。

回答by luke's programmer

gets() is unsafe, for example: char str[1]; gets(str) if you input more then the length, it will end with SIGSEGV. if only can use gets, use malloc as the base variable.

get() 是不安全的,例如: char str[1]; gets(str) 如果您输入的长度大于长度,它将以 SIGSEGV 结尾。如果只能使用gets,则使用malloc 作为基变量。