简单C scanf不工作? [英] Simple C scanf does not work?

查看:203
本文介绍了简单C scanf不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试以下某项:

int anint;
char achar;

printf("\nEnter any integer:");
scanf("%d", &anint);
printf("\nEnter any character:");
scanf("%c", &achar);
printf("\nHello\n");
printf("\nThe integer entered is %d\n", anint);
printf("\nThe char entered is %c\n", achar);

它允许输入一个整数,然后跳过第二个 scanf 完全,这是真的很奇怪,因为当我交换两个( char scanf第一),它工作正常。

It allows entering an integer, then skips the second scanf completely, this is really strange, as when I swap the two (the char scanf first), it works fine. What on earth could be wrong?

推荐答案

使用 scanf 读取输入时, ,在按下返回键之后读取输入,但返回键生成的换行符未被 scanf 消耗,这意味着下次读取<$ c $

When reading input using scanf, the input is read after the return key is pressed but the newline generated by the return key is not consumed by scanf, which means the next time you read a char from standard input there will be a newline ready to be read.

一个可以避免的方法是使用 fgets 以字符串形式读取输入,然后使用 sscanf 解压缩:

One way to avoid is to use fgets to read the input as a string and then extract what you want using sscanf as:

char line[MAX];

printf("\nEnter any integer:");
if( fgets(line,MAX,stdin) && sscanf(line,"%d", &anint)!=1 ) 
   anint=0;

printf("\nEnter any character:");
if( fgets(line,MAX,stdin) && sscanf(line,"%c", &achar)!=1 ) 
   achar=0;

另一种使用换行符的方法是 scanf(%c% * c,& anint); %* c 将从缓冲区中读取换行符并将其舍弃。

Another way to consume the newline would be to scanf("%c%*c",&anint);. The %*c will read the newline from the buffer and discard it.

您可能想读:

C常见问题:为什么每个人都说不使用scanf?

这篇关于简单C scanf不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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