2013-10-05 104 views
0

我应该写在这里指定的程序:我必须按CTRL + D两次才能结束输入,为什么?如何更正?

 
Input 

The 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. 
Output 

For 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 Input 

1 5 
7 2 

Sample Output 

6 
9 

一个我这样写:

 
    #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 )两次结束输入?有没有更好的方法来编写这段代码?

+0

一个EOF用于'scanf'函数,一个用于'getchar'。你需要重新组织你的程序,所以它不会再等两次。 –

回答

0

你的第一个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]); 
} 
0

您的密码不应该依赖EOFgetchar()命中。更改此:

do { 
    scanf("%d %d", &a, &b); 
    ... 
} while((c=getchar())!=EOF); 

到:

do { 
    if (scanf("%d %d", &a, &b) != 2) 
     break; 
    ... 
} while((c = getchar()) != EOF); 

或者你可能会忽略getchar()调用完全:

while (scanf("%d %d", &a, &b) == 2) { 
    ... 
} 
0

scanf()读取您的输入线,它会读取两个数字,但它留下的是终止输入流中的行换行。然后当getchar()读取下一个字符时,它读取换行符。由于换行符不是EOF,它将返回到循环的开头。

现在再次运行scanf(),它会看到您在换行符后键入的EOF。它返回而不更新变量。然后再次调用getchar(),并且必须键入另一个EOF才能获取它。

相关问题