tebi 发表于 2011-3-19 23:42:33

getchar()疑惑???

getchar()疑惑???
我今天编写了个程序,用getchar()函数获得字符,然后根据getchar()获得的字符来确定输出的结果。
具体程序如下:
#include<stdio.h>
void main()
{
int x,i,*p,*py;
char ss;
void sort(int a[],int *px);

printf("Please input 10 numbers:\n");
for(i=0;i<10;i++)
scanf("%d",&x);

p=x;

sort(x,p);

printf("Please input a or d:\n");
getchar();
if(getchar()=='a')
{
for(p=x;p<(&x);p++)
printf("%d",*p);
}

if(getchar()=='d')
{
for(py=&x;py>=&x;py--)
printf("%d",*py);

}
}

void sort(int a[],int *px)
{
int i,j,temp;
for(i=0;i<10;i++)
{
for(j=i;j<10;j++)
{
if(a<*px)
{
temp=*px;
*px=a;
a=temp;
}
}
px++;
}


}
修改后是:
#include<stdio.h>
void main()
{
int x,i,*p,*py;
char ss;
void sort(int a[],int *px);

printf("Please input 10 numbers:\n");
for(i=0;i<10;i++)
scanf("%d",&x);

p=x;

sort(x,p);

printf("Please input a or d:\n");

if(getchar()=='a')
{
for(p=x;p<(&x);p++)
printf("%d",*p);
}

if(getchar()=='d')
{
for(py=&x;py>=&x;py--)
printf("%d",*py);

}
}

void sort(int a[],int *px)
{
int i,j,temp;
for(i=0;i<10;i++)
{
for(j=i;j<10;j++)
{
if(a<*px)
{
temp=*px;
*px=a;
a=temp;
}
}
px++;
}


}
这个是经人指点后的修改。不明白为什么?
错误的程序,输入d后回车确认,没有任何结果。所以想详细了解下getchar()的用法,和为什么会错。

小甲鱼 发表于 2011-3-20 13:04:01

#include<stdio.h>
void main()
{
      int x, i, *p, *py;
      char ss;
      void sort(int a[],int *px);
      
      printf("Please input 10 numbers:\n");

      for( i=0; i < 10; i++)
      {
            scanf("%d", &x);
      }
      p = x;
      
      sort( x, p );
      
      printf("Please input a or d:\n");

      ss = getch();

      if( ss == 'a' )
      {
            for( p=x; p < &x; p++)
            {
                  printf("%d", *p);
            }
      }
      printf("\n");
      
      if( ss == 'd' )
      {
            for( py=&x; py >= &x; py--)
            {
                  printf("%d", *py);
            }
      }
      printf("\n");
}

void sort(int a[],int *px)
{
      int i, j, temp;
      for( i=0; i < 10; i++)
      {
            for( j=i; j < 10; j++)
            {
                  if( a < *px)
                  {
                        temp = *px;
                        *px = a;
                        a = temp;
                  }
            }
            px++;
      }
      
      
}帮你整理格式花了不少时间,下次注意点格式哦~

getchar()是从键盘缓冲区读取字符,并作为返回值返回的,这里因为前边输入的干扰,键盘缓冲区不正常。
所以if( getchar() == 'a' )读入的是缓冲区里边的内容,当提示输入a或者d的时候程序是停留在if( getchar() == 'd' )的判断上。
因此,会产生输入a不显示任何东西的情况,而输入d正常。
这样我们就不能使用读取缓冲区的函数,改成getch()就可以。

f314191434 发表于 2011-3-21 22:04:26

小甲鱼的程序格式很美观易懂,灰常支持!

LZ还可以加上这个语句:   fflush(stdin);//清除缓冲
之后就可以依旧用getchar();

追梦1航海 发表于 2014-3-17 11:34:12

解释的不错,不过用getch()要函数头 stdlib哦,用getchar不需要
页: [1]
查看完整版本: getchar()疑惑???