C语言 为什么scanf对字符输入的行为很奇怪


/* Write macro for the following : 
1. Arithmetic Mean of two no.
2. Absolute value of a no.
3. To convert a Uppercase letter to lower case.
4. To obtain bigger of two numbers.
*/
#include<stdio.h>
#define am(a,b) ((a+b)/2)
#define abs(a) (a>=0?a:-a)
#define ul(ch) (ch>=65 && ch<=96 ? ch+32 : ch)
#define bigger(a,b) (a>=b?a:b)
int main () {
    int x,y;
    char c;
    printf("nEnter two numbers:");
            scanf("%d%d",&x,&y);
    printf("nThe arithmetic mean of two numbers is %f",(float)am(x,y));
    printf("nEnter the number:");
            scanf("%d",&x);
    printf("nThe absolute value of the number is %d",abs(x));
    printf("nEnter the character:");
            scanf("%c",&c);
    printf("nThe letter in lower case  is %c",ul(c));
    printf("nEnter two numbers:");
            scanf("%d%d",&x,&y);
    printf("nThe bigger of two numbers is %d",bigger(x,y));

 return 0;
 }

一切正常,只是程序在接受字符输入时没有停止。

下面是输出的快照....

  Enter two numbers:4
  5
  The arithmetic mean of two numbers is 4.000000
  Enter the number:-7   **/*After hitting enter here it reaches line no. 7 */** 
  The absolute value of the number is 7
  Enter the character:                                          
  The letter in lower case  is  
  Enter two numbers:4   **/*line no. 7*/**
  6
  The bigger of two numbers is 6

这是因为%d跳过空白,而%c没有——或者换句话说。

%d将跳过输入流中任何继续的空白,然后输入指针将在最后一个数字之后——这很可能是您的换行符。所以当你来请求%c时,你实际上已经有了输入数据——那是你的换行符——那就是你将要读到的。

更改scanf,通过在%c前插入空格来要求它跳过空白,因此

   scanf(" %c",&c);

我认为这里的问题是您的scanf("%c",&c)正在抓取当您按回车键输入-7时输入的回车。

在scanf前面放一个getchar(或另一个scanf("%c",&c)),你就不会有这个问题了

%c读取包括换行符在内的任何字符,因此它将"吃掉"换行符。

用法:scanf(" %c",&c);

scanf的一个常见问题是它不使用按回车所产生的换行符。我通常通过在调用scanf

后使用以下宏来绕过它
#define consumeBuffer() while (getchar() != 'n');

当然,这并不总是你想要的,但在大多数情况下,它会达到目的。

这是因为在您的第一个scanf之后,输入键仍然在输入缓冲区中,而下一个scanf将在x中存储输入值。然后你的下一个printf将打印它-有效地移动到新的行。

要解决这个问题,您可以在每个scanf之后添加一个getchar()调用。

最新更新