简体   繁体   English

如何解决 C 中的 gets() function 的问题?

[英]How can I fix the problem with gets() function in C?

There is a problem with gets function. gets function 存在问题。 The first gets I write does not work but the ones comes next works properly.gets的第一个不工作,但接下来的工作正常。

I put an extra gets() function at the beginning, program just skips it and gets the string I want.我在开头放了一个额外的gets() function,程序只是跳过它并获取我想要的字符串。 But it is not safe and reliable.但它并不安全可靠。 So what is the problem with gets and how can I fix it?那么gets有什么问题,我该如何解决呢?

if (choice == 1) {
  printf("Please enter an English phrase with upper case: ");
  gets(a);
  gets(engphr);
  for (i = 0; engphr[i] != '\0'; i++) {

As Eraklon mentions in their comment, the most likely cause is that you have a scanf call before the gets call, and the trailing newline from the previous input is getting consumed by gets before you have a chance to enter anything else.正如 Eraklon 在他们的评论中提到的那样,最可能的原因是您在调用gets之前有一个scanf调用,并且gets您有机会输入其他任何内容之前,来自先前输入的尾随换行符已被 get 消耗。

You should never use gets anyway - it was removed from the standard library in the 2011 version of the language.无论如何,您都不应该使用gets - 它已从 2011 版语言的标准库中删除。 It is inherently unsafe to use, and will introduce a security hole in your code.使用它本质上是不安全的,并且在您的代码中引入安全漏洞。 Use fgets instead.请改用fgets Its behavior is slightly different (it will save the trailing newline to the input buffer if there's room, where gets discarded it), but it's much safer:它的行为略有不同(如果有空间,它会将尾随换行符保存到输入缓冲区,在哪里gets丢弃),但它更安全:

if ( fgets( engphr, sizeof engphr, stdin ) ) // assumes engphr is declared as an array, not a pointer
{
  // process engphr
}

Having said that, you really shouldn't mix calls to scanf and fgets , again because scanf will leave trailing newlines in the input stream from previous inputs, and fgets will immediately return after seeing that newline.话虽如此,您真的不应该混合对scanffgets的调用,因为scanf会在输入 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 中留下来自先前输入的尾随换行符,并且fgets将在看到该换行符后立即返回。 Either read all input using fgets and use sscanf to read specific items from the input buffer, or read all input with scanf .使用fgets读取所有输入并使用sscanf从输入缓冲区中读取特定项目,或者使用scanf读取所有输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM