Input using gets not working, but working with sca

2019-07-15 19:37发布

问题:

#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.



标签: c gcc input stdin