scanf()的功能不起作用? [英] scanf() function doesn't work?

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

问题描述

这可能是一个简单的问题,但我搜索了很多,仍然没有搞清楚。
我从终端gcc和运行程序编译如下剪断code。在正确的,它允许进入一个int和一个char,但事实并非如此。它不会等待进入炭??

This may be a simple question, but i searched a lot and still didn't figure it out. I compiles below snip code by gcc and run program from terminal. In correct, It allow to enter an int and a char but it doesn't. It doesn't wait to enter the char??

这里有人可以帮我定样。在此先感谢!

Anyone here can help me will be kind. thanks in advance!

#include <stdio.h>

int main()
{

  char c;
  int i;

  // a
  printf("i: ");
  fflush(stdin); scanf("%d", &i);

  // b
  printf("c: ");
  fflush(stdin); scanf("%c", &c);

  return 0;

}

推荐答案

%d个将读取连续的数字,直到遇到一个非数字。 %C 读取一个字符。可能发生的事情是,你给它下一个新的行数(数位)。 %C 然后读取该新行。你可能是打算为 fflush(标准输入); 丢弃任何还没有被读取,但不幸的是,的这是不确定的行为

%d will read consecutive digits until it encounters a non-digit. %c reads one character. Probably what's happening is that you're giving it a number (several digits) followed by a new line. %c then reads in that new line. You were probably intending for the fflush(stdin); to discard anything that hadn't yet been read, but unfortunately, that's undefined behavior.

解决方案是读取字符前放弃所有空白:

The solution is to discard all whitespace before reading the character:

scanf(" %c", &c);

请注意在开始的空间。这意味着放弃所有的空白。

Note the space at the start. That means to discard all whitespace.

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

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