Question

I have a litte problem with EOF. I need to write numbers in one line with spaces between them and sum them together. Scanf must be ended with one EOF (Ctrl+D) I have this 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 with this program is that I need to press Ctrl+d two times until it prints sum.

Example input/output:

Enter numbers: 1 3 5 6 <'Ctrl+d'>

15.00

Was it helpful?

Solution

EOF must be preceded with a newline else it won't work. However it depends on the OS. The EOF you enter at the end of of the line containing the input is not recognized. From the man page of scanf -

scanf returns the number of items successfully matched and assigned which can be fewer than provided for, or even zero in the event of an early matching failure. The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.

Therefore you should check the return value of scanf for 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);
}

OTHER TIPS

scanf returns the number of values it assigned; so if you want to use that, you want

while (scanf("%lf", &numbers) == 1)

Alternatively, you could use more of a C++ idiom (assuming you meant to tag the question with that language as well as C):

while (std::cin >> numbers)

The program is showing this behavior because, when you give input
4 4 4 scanf() will not start reading input. scanf() starts reading input when you press [enter]. so if you give input as
4
4
4
then the result will come on first
otherwise you will need 2 's since first one starts reading input and it wont be read as EOF as it just makes scanf() start reading input. therefore one more will be read by scanf() as EOF.

The stdin EOF flag won't be turned on until the second ctrl+d in succession, the first ctrl+d pushes whatever is on your screen to the stdin buffer, the second ctrl+d sets the EOF flag.

In another case, when you enter some numbers and press enter, the numbers on your screen is pushed to the stdin input buffer, and ctrl+d soon after will also set the EOF flag.

On your system this is normal behaviour, the EOF only occurs on the second ctrl+d.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top