cya
cya

Reputation: 258

How to read multiple integers from a single line?

Input is some integers separeted by spaces in one line, like this:

   enter numbers: 12 41 2

program should get each integers and show the sum:

   sum: 55

how can i do that?

edit:I tried this but it is unable to detect enter key. It should stop and show sum when enter is pressed.

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

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

Upvotes: 0

Views: 8492

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40155

#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;
}

Upvotes: 1

BLUEPIXY
BLUEPIXY

Reputation: 40155

#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;
}

Upvotes: 1

Related Questions