Entering char with scanf and saving it to int can cause undefined behavior?

I am working on code and I tried to type char instead of integer, and the result was "2" regardless of the character entered, is this behavior undefined or something else?

The code:

#include <stdio.h>
int f1(int n);
int f2(void);

int main(void)
{
    int t;

    printf("Enter a number: ");
    scanf("%d", &t);
    /* print proper message */
    t ? f1(t) + f2() : printf("zero entered.\n");
    return 0;
}

int f1(int n)
{
    printf("%d ", n);
    return 0;
}

int f2(void)
{
    printf("entered.\n");
    return 0;
}

when I entered a, the result was “2 entered”, and when I entered g, the result was “2 entered”, and when I entered i,h,k,....., the result was the same. What is it?

0
source share
5 answers

This is because scanfyour input could not be parsed. He expects you to enter decimal digits , as you used %d.

scanf, :

. ( ) - , .

:

int items_matched;

// ...
items_matched = scanf("%d", &t);   // Get the return value

if ( items_matched != 1 )          // Check it
{
    printf("Matching failure with scanf.\n");
    return 0;
}
else
{
    if ( t == 0 )
        printf("zero entered\n");
    else
        printf("%d entered\n", t);
}

f1(t) + f2(), ...

0

scanf() -, , . t ( , t ).

, scanf.

+3

, , , scanf % d ascii. , , , , t , , scant.

0

scanf. manpage:

, , , .

EOF , , . EOF , , (. Ferror (3)), errno .

, scanf t, .

, :

scanf("%d", &t);

:

int items_matched = scanf("%d", &t);
if (items_matched != 1) {
    printf("bad number entered\n");
    exit(1);
}
0

Linux man

, . , , scanf() . "" : , , , , .

C11 scanf (7.21.6.4 scanf) 3:

The scanf function returns the value of the EOF macro if the input fails before the first conversion is completed (if any). Otherwise, the scanf function returns the number of input elements assigned, which may be less than provided, or even zero, in an early match event .

The emphasis is mine. Since @oli charlesworth said you should check the return value of scanf if in doubt :)

0
source

All Articles