为什么scanf函数的行为怪异字符的输入? [英] Why scanf is behaving weird for char input?

查看:131
本文介绍了为什么scanf函数的行为怪异字符的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  / *以下写的宏:1.二没的算术平均值。
2.没有绝对值。
3.要一个大写字母转换为小写。
4.为了获得更大的两个数字。* /#包括LT&;&stdio.h中GT;的#define点(A,B)((A + B)/ 2)
#定义ABS(A)(A> = 0:-a?)
UL的#define(CH)(CH> = 65安培;&安培; CH< = 96 + CH 32:CH)
#定义较大(A,B)(A> = B A:B)诠释主(){    INT X,Y;
    焦炭℃;    的printf(\\ n输入两个数字:);
            scanf函数(%D,&安培; X,&安培; Y);    输出(两个数\\ n该算术平均值%F,(浮点)上午(X,Y));    的printf(\\ n输入数字:);
            scanf函数(%d个,&安培; X);    输出(数\\ n该绝对值为%d,ABS(X));    的printf(\\ n输入的字符:);
            scanf函数(%C,和C);    的printf(小写\\ n此信是%C,UL(C));    的printf(\\ n输入两个数字:);
            scanf函数(%D,&安培; X,&安培; Y);    的printf(\\ n该更大两个数为%d,更大(X,Y));
 返回0; }

一切正常,只是程序采取字符输入不会停止。

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

 输入两个数字:4
  五
  两个数的算术平均值是4.000000  输入号码:-7 ** / *按下回车键在这里它达到线没有了。 7 * / **
  数的绝对值是7  输入字符:
  小写字母是  输入两个数字:4 ** / *号线。 7 * / **
  6  两个数字的更大的是6


解决方案

我相信这里的问题是,你的scanf函数(%C,和C)被抓住了回车进入,当你按下回车键放于-7。

将一个getchar函数(或其他scanf函数(%C,和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;

 }

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

解决方案

I believe the problem here is that your scanf("%c",&c) is grabbing the carriage return entered when you hit enter to put in the -7.

Put a getchar (or another scanf("%c",&c)) right before the scanf and you shouldn't have that problem.

这篇关于为什么scanf函数的行为怪异字符的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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