如何从一行读取多个整数?

时间:2014-04-11 22:14:24

标签: c input

输入是一行中由空格分隔的整数,如下所示:

   enter numbers: 12 41 2

程序应该得到每个整数并显示总和:

   sum: 55

我该怎么做?

编辑:我试过这个但是无法检测回车键。当按下输入时,它应该停止并显示总和。

printf("\nEnter numbers: ");
int sum =0;
int temp;
while( scanf("%d",&temp))
{
    sum+=temp;

}
printf("Sum: %d",sum);

2 个答案:

答案 0 :(得分:1)

#include <stdio.h>

int main(void){
    char line[128], *p=line;
    int sum = 0, len, n;

    printf("enter numbers: ");
    scanf("%127[^\n]", line);
    while (sscanf(p, "%d%n", &n, &len)==1){
        sum += n;
        p += len;
    }
    printf("sum: %d\n", sum);
    return 0;
}

答案 1 :(得分:1)

#include <stdio.h>

int main(){
    printf("\nEnter numbers: ");
    int sum =0, temp;
    char ch;
    while(2 == scanf("%d%c", &temp, &ch)){
        sum+=temp;
        if(ch == '\n')
            break;
        else if(ch != ' '){
            fprintf(stderr, "Invalid input.\n");
            return -1;
        }
    }
    printf("Sum: %d\n", sum);
    return 0;
}