Input using gets not working, but working with scanf

家住魔仙堡 提交于 2019-12-10 23:21:50

问题


#include<stdio.h>
void main(){
  char str[100];
  char letter;
  letter=getchar();
  printf("%c",letter);
  gets(str);
  //Rest of code
}

On execution, the code skips the gets(str) line. But when I replace gets by scanf, it works. Any specific reason why that doesnt work? I am using gcc 4.7.2.


回答1:


The first call to getchar() leaves a newline character in the input buffer. The next call gets() considers that newline as end of input and hence doesn't wait for you to input.

Consume the newline character using another getchar().

 ...
 letter=getchar();
 getchar(); // To consume a newline char left
 printf("%c",letter);
 fgets(str, sizeof str, stdin);

Note: gets() is dangerous as its vulnerable against buffer overflow. So use fgets() instead.




回答2:


as answered above when you read a character from statndard input the enter you hit after this is placed in stdin buffer which was read by gets() in your case . that is why gets() is not waiting for input.

you can use fflush(stdin) to clear the input buffer after reading the character .




回答3:


getchar() leaves a trailing line feed character '\n' in stdin. When you call gets(), it reads until it encounters such a line feed character, which it discards. Since the first character it reads is '\n', it immediately stops there.

The solution is to make a dummy read to discard the line feed character:

#include <stdio.h>

int main ()
{
  char str[100];
  char letter;

  letter=getchar();
  getchar();

  printf("%c",letter);

  gets(str);
  return 0;
}

Please note that void main() is not valid C (unless you are developing a free running embedded system, which seems unlikely in this case). More info here.

Please note that the gets() function is no longer part of the C language, it was removed with the C11 version of the standard. Use fgets() instead.



来源:https://stackoverflow.com/questions/16300121/input-using-gets-not-working-but-working-with-scanf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!