getchar is able to read ctrl+z but not scanf?

37 views Asked by At

What I want to do is find out if scanf can read ctrl+z as EOF? I know that getchar and scanf return EOF when the end of the file is reached. This I have no problem with. What I want to do is have them read EOF or ctrl+z to the parameter(and not look at the return-value), is this possible?

First I have this code:

#include <stdio.h>

int main(void) {

    int d;

    d = getchar();
    printf("%d\n", d);

}

/*Output:
^Z
-1
*/

As you can see there is no problem with getchar. But with scanf I get this:

#include <stdio.h>

int main(void) {
    
    int d;

    scanf_s("%d", &d);
    printf("%d\n", d);

}
/*
Output:
^Z

*/

Nothing happens when I press ctrl+z and hit enter. Could you please explain why it works with getchar but not with scanf?, and what must I do to make it work?

0

There are 0 answers