blackroad blackroad - 7 days ago 5
C Question

while and eof won't work

my while cyclus wont work when i want to close it with CTRL+C

while(1){
res=scanf("%d",&k);
if(res != 1){
printf("Bad input.\n")
return 1;
}
else if((k <= 0)){
printf("Bad input.\n");
return 1;
}
if(res == EOF){
return 0;
}
a=one(arr, arr_size, k);
b=two(arr, arr_size, k);
c=three(arr, arr_size, k);
printf("Sum: %d\n",a+b+c);
}


It just shows me Bad input when I want to close it CTRL+D. I want only to close program with
return 0;

Answer

The first test you do is on res, and EOF is in fact just the number -1, which is not equal to 1, causing the first if to resolve to true and returning with 1.

This should work:

while(1) {
    res=scanf("%d",&k); 

    /* first check for EOF */
    if(res == EOF){
        return 0;
    }
    /* then check input */
    if(res != 1 || k <= 0) {
        printf("Bad input.\n");
        return 1;
    }
}