gpt4 book ai didi

c - 如何从标准输入读取数字直到结束

转载 作者:行者123 更新时间:2023-11-30 19:17:05 25 4
gpt4 key购买 nike

在有 for(;;) 的地方,我需要从 stdin 读取一些内容并保存到 N。可能有 read(stdin,N,sizeof(float))while(s!=EOF) s=getc(stdin) 吗? 我假设数字列表保存在标准输入分隔的行尾

问题是这样的:

Your program must print its pid to standard output. Then it should start to read values of N from standard input until the end of the file. After receiving a signal (SIGUSR1) your program should subtract (then multiply, then divide, then subtract) the value of N from sum (first value of sum=0) as a cycle. After receiving SIGUSR2 your program should print the current sum.

我如何解释问题和尝试:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

float N,sum=0;
int count=0;

void handler(int s){
count++;
if (s==SIGUSR1){
if (count==1){
sum-=N;
}
if (count==2){
sum*=N;
}
if (count==3){
sum/=N;
}
if (count==4){
sum+=N;
count==0;
}

}

else if (s==SIGUSR2){
printf("sum=%d",sum);
}
}


int main(){
pid_t pid=getpid();
signal(SIGUSR1,handler);
signal(SIGUSR2,handler);
printf("%d",pid);
fflush(stdout);

for(;;)
scanf("%d",&N);


return(0);
}

最佳答案

检查scanf的返回值。它返回成功匹配的项目数,因此如果它不返回 1,那么就完成了。

while (scanf("%d", &N) == 1)
;

关于c - 如何从标准输入读取数字直到结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28731746/

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