读书人

getchar ()函数的用法!解决方法

发布时间: 2013-03-04 17:22:12 作者: rapoo

getchar ()函数的用法!

# include <stdio.h>

void action1 (int ,int );
void action2 (int ,int );

int main ()
{
char ch;
int a,b;


printf ("two indegits are :");
scanf ("%d %d", &a, &b);
printf ("your choose is (a/b):\n");
ch = getchar(); //这里用个getchar ()函数正确吗? 执行文件时,有问题!!

switch (ch)
{
case 'a':
case 'A': action1 (a,b); break;
case 'b':
case 'B': action2 (a,b); break;
default: printf ("wrong ");

}
printf (" the result is ");
return 0;
}
void action1 (int a ,int b)
{
printf ("%d\n",a+b);
return ;
}
void action2 (int a,int b)
{
printf ("%d\n",a*b);
return ;
}

[解决办法]
由于前面有个scanf,所以输入流中是有一个‘\n’未被读取的,所以你可以在其后紧跟一个getchar();语句
[解决办法]
你可以在ch=getchar()前面加一句fflush(stdin);吃掉那个回车,虽然这不是符合C标准的方法,但是TC和VC都可以。
[解决办法]
这个有时候会出问题,要确保不出问题可以用scanf,如果一定要使用getchar,那最好前面再加一个getchar();写成这样的
printf ("your choose is (a/b):\n");
getchar();//这里可会有前一个scanf留下的垃圾'\n',回收下
ch = getchar();
这样应该就不会有问题了
[解决办法]
应该消除输入流fflush(stdin);

读书人网 >C语言

热点推荐