kyle k
kyle k

Reputation: 5512

c program giving 32767 for letters

My C program is giving the number "32767" when I enter a letter, but when I enter an integer it tells me the number that I entered.

why will my program not tell me what letters I entered? why is it giving me the number "32767"?

#include <stdio.h>

main()
{
    int number;

    printf("Enter an integer\n");
    scanf("%d",&number);

    printf("Integer entered by you is %d\n", number);

    return 0;
}

Upvotes: 0

Views: 1077

Answers (3)

carlos
carlos

Reputation: 1

If you want printf() to display characters and scanf() to get that data, you must point that it's a character, using "char" instead of "int" and use "%c" instead of "%d".

Something like this (I still used the "number" variable and the description in the printf() about the " integer":

#include <stdio.h>

main()
{
    char number;

    printf("Enter an integer\n");
    scanf("%c",&number);

    printf("Integer entered by you is %c\n", number);

    return 0;
}

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129344

What you are seeing is "undefined behaviour", which pretty much means "anything can happen". The value in number, in particular, can have any value, because it has not been initialized. If you initialize it int number = 42; it will (probably) print 42, but I'm not sure that's guaranteed.

Upvotes: 0

Drew McGowen
Drew McGowen

Reputation: 11706

If scanf doesn't find what it's looking for (in this case, an int), it will simply return without modifying whatever gets passed in. In other words, scanf won't change number, so it'll have it's old value, which, in this case, is undefined (since it's not initialized).

Upvotes: 2

Related Questions