gpt4 book ai didi

c - 我必须按两次CTRL+D才能结束输入,为什么?如何更正?

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

我应该编写一个此处指定的程序:

InputThe input will consist of a series of pairs of integers a and b,separated by a space, one pair of integers per line. you should read the input until EOF.OutputFor each pair of input integers a and b you should output the sum of a and b in one line,and with one line of output for each line in input.Sample Input1 57 2Sample Output69

an I write this:

     #include 

 main() {
int a, b;
int sum[100];
int i,j;
char c;

for(i=0; i<100; i++) sum[i]=0;

i=0;
do {
scanf("%d %d", &a, &b);
sum[i]=a+b;
i++;
} while((c=getchar())!=EOF);

for(j=0; j<i-1; j++) printf("%d\n", sum[j]);
}

令我奇怪的是:为什么要按两次 CTRL+D(EOF) 来结束输入?有没有更好的方法来编写这段代码?

最佳答案

你的第一个 CTRL-D 破坏了 scanf。之后你的程序在 getchar 中等待。如果您检查 scanf 的输出,则只有一项检查。

#include <stdio.h>


main() {
int a, b;
int sum[100];
int i,j;
char c;

for(i=0; i<100; i++) sum[i]=0;

i=0;
while ( 2==scanf("%d %d", &a, &b))
{
sum[i]=a+b;
i++;
}

for(j=0; j<i-1; j++) printf("%d\n", sum[j]);
}

关于c - 我必须按两次CTRL+D才能结束输入,为什么?如何更正?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19197013/

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