Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
919 views
in Technique[技术] by (71.8m points)

c - Why scanf is behaving weird for char input?

/* 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("
Enter two numbers:");
            scanf("%d%d",&x,&y);

    printf("
The arithmetic mean of two numbers is %f",(float)am(x,y));

    printf("
Enter the number:");
            scanf("%d",&x);

    printf("
The absolute value of the number is %d",abs(x));

    printf("
Enter the character:");
            scanf("%c",&c);

    printf("
The letter in lower case  is %c",ul(c));

    printf("
Enter two numbers:");
            scanf("%d%d",&x,&y);

    printf("
The bigger of two numbers is %d",bigger(x,y));


 return 0;

 }

Everything is working fine except that program does not stop for taking character input.

Here is the snapshot of the output ....

  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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is because the %d skips white space, but %c does not -- or in other words.

The %d will skip any proceeding white space in your input stream, and the input pointer will be then just after the last digit -- which is most likely you newline. So when you come to ask for the %c you will actually already have input data -- that is your newline -- and that is what you will read.

change your scanf to ask it to skip white space by just inserting a space before the %c, so

   scanf(" %c",&c);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...