Expected Program to Print EOF Values

In code:

#include<stdio.h> int main() { int t; for(;scanf("%d",&t);printf("%d",t)); } 

The program works as expected when I give general queries as input. I am working on Windows, so when I scan Cntrl + Z for the argument t, I do not get the value EOF ie -1 on the standard output, but the previous argument that was stored in it. Also, when I press Cntrl + D, the program ends, why does Cntrl + D force scanf to return 0?

And why on scanf Cntrl + C my compiler says: "The process has completed with the status -107 ......" I do not understand why this is happening? Please, help.

+4
source share
2 answers

scanf returns the number of successfully matched formatting specifiers or EOF if the end of the input was reached before the match (or mismatch) of the first qualifier.

When you press Ctrl + Z, scanf reaches the end of the input and returns EOF (because Ctrl + Z completes the input on Windows). This does not end the for loop because EOF is nonzero, therefore the previous value of t is output (since t not changed by the call). Note that t will not get the EOF value at the end of the input, as you expect: scanf returns EOF as the return value, it does not write it to the pointers that you pass to it.

When you press Ctrl + D, it is treated like any other character. Since it is not numeric, it causes a corresponding failure for the %d specifier and scanf returns 0, which completes the loop.

+6
source

Try this code, and when you press CTL + Z (CTL + D on linux), you will get zero. otherwise prints 1

 #include <stdio.h> main() { int c; while(c=getchar()!=EOF) //here get the character and then compares with the EOF if Not equal 1 will assign to c , if equal 0 will assign to c. printf("%d",c); printf("%d",c);//when ever we press ctl+Z(ctl+d on linux) then it will print zero remaing all cases this statement wont execute getchar(); } 
0
source

Source: https://habr.com/ru/post/1499406/


All Articles