简体   繁体   中英

difference between scanf(“%c” , ..) and getchar()

I always think scanf("%c" , &addr); is equal to getchar() before I test this:

#include<stdio.h>

int main()
{
    int i;
    scanf("%c",&i);
    printf("%d\n", i);
    if(i == EOF)
        printf("EOF int type and char input\n");
    i =getchar();
    printf("%d\n", i);
    if(i == EOF)
        printf("EOF int type and char input\n");
}

I got output when I use "Ctrl+D" twice:

-1217114112

-1

EOF int type and char input

Since EOF is -1 in int type ,I also try use scanf("%d",&i); replace scanf("%c",&i) , just get the same output.

I got confused. Can anybody explain this for me?

----------------------------------EDIT-----------------------------------------------

I want to know the behavior of scanf("%c",i) of Ctrl+D , I do test:

#include<stdio.h>

int main()
{
    int i;
    int j;
    j = scanf("%c",&i);
    printf("%c\n", i);
    printf("%d\n", j);
    if(i == EOF)
        printf("EOF int type and char input");
     i =getchar();
    printf("%d\n", i);
    if(i == EOF)
        printf("EOF int type and char input");
}

OutPut:

k                  // If the scanf set 1 byte in i , why here print 'k' ?
-1
-1
EOF int type and char input

The first value is probably undefined behavior. You can't rely on i having a value unless scanf() returns 1.

With scanf() in particular, you seem to be confusing the scanned value (the conversion of characters according to a format specifier in the first argument) with the return value of the function call.

With getchar() , of course, this distinction doesn't exist since it only has a return value.

Your comparison does not fully set i as it involves Undefined Behavior (UB).

int i;            // the value of i could be anything
scanf("%c",&i);   // At most, only 1 byte of i is set, the remaining bytes are still unknown.
printf("%d\n", i);// Your are printing 'i' whose value is not fully determined.

Had you tried

char ch;
int y = scanf("%c",&ch);
printf("%d\n", ch);
if(ch == EOF)

You would potentially make a match even though the input was not EOF. Had you scanned in a char with the value of 255, the char would take on the 2s compliment 8-bit value of -1. The comparison would sign extend the 8-bit -1 to match the int size and you would match -1.
(Assumptions: 2s compliment integers, 8-bit byte, EOF == -1, char is signed).

The correct EOF test is

int y = scanf("%c",&ch);
if (y == EOF)

Note: getchar() & scanf() return EOF implies End-of-file or I/O error. A subsequent check of ferror(stdin) distinguishes this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM