while函数中的getchar()函数出现新问题之三!(linux版),请教!
各位前辈周末好,小弟的又碰见了新问题,这回是给运行环境有关的,请看代码:
struct data_structure
{
int p;
int q;
};
typedef struct data_structure ds;
ds* get_input(ds* a,int num)
{
int n = 0,j;
char p1,q1;
if(a==NULL)
return -1;
memset(a, 0, sizeof(ds)*num);
printf("Please input the %d group data ",num);
printf("(input 'x' to exit!).\n");
while(n<num)
{
printf("p = ");
fflush(stdin);
p1 = getchar(); // 请注意这里的getchar函数
if((p1=='X')||(p1=='x'))
break;
if(isdigit(p1))
a[n].p = p1-0x30;
printf("q = ");
fflush(stdin);
q1 = getchar(); // 请注意这里的getchar函数
if((q1=='X')||(q1=='x'))
break;
if(isdigit(q1))
a[n].q = q1-0x30;
n++;
};
return a;
};
本人想让每次输入的数分别放入一个结构数组中的p,q里去,在windows下的VC调试和运行现在都很正确,可一旦我将该程序移到linux环境下的时候,运行结果就不对了。
在windows下,程序中的两个getchar函数都正确地执行了,但到了linux下,用gcc编译以后,程序每次执行循环时确显示以下语句:
p = q =_
这也就是说其中有一个getchar函数没有执行。我认为可能还是跟getchar函数和缓冲区有关,但小弟实在对linux系统不熟,请指教!
问题点数:100、回复次数:1Top
1 楼Francky(寒星)回复于 2002-05-11 22:27:16 得分 100
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
main()
{
char c;
int iflg;
FILE *fp;
if( (fp=fopen("test.out","w"))==NULL)
{
perror("fopen FATAL");
exit(0);
}
printf("fileno(stdin)=%d\n",fileno(stdin));
iflg = fcntl(fileno(stdin),F_GETFL,0);
if(iflg == -1)
{
perror("fcntl(F_GETFL) FATAL");
}
if(fcntl(fileno(stdin),F_SETFL,iflg|O_NONBLOCK)==-1)
{
perror("fcntl(F_SETFL) FATAL");
}
printf("hello");
c=getchar();
printf("%c\n",c);
}
看看这段代码吧。
Top




