c - Exiting scanf loop with numbers in one line with one EOF -


i have litte problem eof. need write numbers in 1 line spaces between them , sum them together. scanf must ended 1 eof (ctrl+d) have little program

#include <stdio.h> #include <stdlib.h>  int main(int argc, char** argv){     double numbers=0, sum=0;         printf("enter numbers: ");     while(scanf("%lf", &numbers) != eof){            sum=sum+numbers;     }     printf("\n %.2lf", sum); } 

problem program need press ctrl+d 2 times until prints sum.

example input/output:

enter numbers: 1 3 5 6 <'ctrl+d'>

15.00

eof must preceded newline else won't work. depends on os. eof enter @ end of of line containing input not recognized. man page of scanf -

scanf returns number of items matched , assigned can fewer provided for, or 0 in event of matching failure. value eof returned if end of input reached before either first successful conversion or matching failure occurs.

therefore should check return value of scanf 1, not eof.

#include <stdio.h>  int main(void) {     double numbers = 0, sum = 0;         printf("enter numbers: ");     while(scanf("%lf", &numbers) == 1) {            sum += numbers;     }     printf("\n %.2lf", sum); } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -