使用get的输入不起作用,但使用scanf [英] Input using gets not working, but working with scanf

查看:134
本文介绍了使用get的输入不起作用,但使用scanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

执行时,代码跳过(str)线。但是当我用scanf替换get时,它就可以工作。任何具体原因为什么不起作用?
我正在使用gcc 4.7.2。

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.

推荐答案

使用另一个getchar()来使用换行符。

Consume the newline character using another getchar().

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

注意 gets()是危险的,因为它容易受到缓冲区溢出的影响。因此,请使用 fgets()

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

这篇关于使用get的输入不起作用,但使用scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆