gpt4 book ai didi

c - scanf 在报告中不起作用

转载 作者:行者123 更新时间:2023-11-30 20:41:52 26 4
gpt4 key购买 nike

#include <stdio.h>
#include <unistd.h>
//#include <iostream.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>

int t_array[100];
int h_array[100];
int race_length=0;

void cursor(int y)
{
int i;
printf("%c[%d;%df",0x1B,y,0);
}

void turtle_fun()
{
int Ti=0;

while(Ti<=race_length-1)
{
//cursor(10);
// printf("t ");
// fflush(stdout);
Ti++;
sleep(3);
}

}

void hare_fun(int rh[])
{
int k;
int i=0;
char pos_h;

while(i<=race_length-1)
{
// cursor(5);
//printf("h ");
// fflush(stdout);
read(rh[0],&pos_h,1);
if(pos_h==1) write(rh[1],&i,1);
i++;
sleep(1);
}

}

void god_fun(pid_t id)
{
}

void report_fun(int rh[],int rg[],int rt[])
{
int k,m,pos;
int pos_h,pos_t;

close(rh[1]);

if(k=fork()==0) hare_fun(rh);
else
{
if(fork()==0) turtle_fun();
else
{
printf("press 1 to know current position \n");
fflush(stdout);
scanf("%d\n",&pos);

if(pos==1) write(rh[1],&pos,1);

read(rh[0],&pos_h,1);
printf("H%d|T\n",pos_h);
printf("j");

//while(h_comp!=1||c!=1);*/
}

}

}

void main()
{
int rg[2],rh[2],rt[2],gh[2],gt[2],ht[2];
int child_id;
pid_t cpid;

printf("what is the length of the race");
scanf("%d",&race_length);
cpid=fork();

if(cpid==0)
{
pipe(rg);
pipe(rh);
pipe(rt);
report_fun(rh,rg,rt);
}
else
{
pipe(gh);
pipe(gt);
god_fun(cpid);
}

}

最佳答案

请勿在 scanf() 格式字符串中包含 \n,这可能会导致您的程序等待两次输入。

所以在report_fun()中改变

scanf("%d\n",&pos);

scanf("%d",&pos);

更新

main() 中,您在子进程而不是父进程中调用 report_fun()。您可能想要反转 if (cpuid == 0) 测试。

请使用 int main(void) 而不是 void main() 并以 return 0; 结束主函数。

关于c - scanf 在报告中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3441700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com