paulakis
paulakis

Reputation: 89

printf() presents weird results

My code is this

#include<stdio.h>
int main(void)
{
    unsigned short height = 0;
    unsigned short width = 0;
    const unsigned short MIN_SIZE = 3;
    printf("Enter the values for the width and the height minimum of %u\n:",
           MIN_SIZE);
    scanf(" %hd %hd", &width, &height);
    if (width < MIN_SIZE)
    {
        printf("The value of width   %u is too small. I set this to %u    \n",
               width, MIN_SIZE);
        width = MIN_SIZE;
    }
    if (height < MIN_SIZE)
    {
        printf
            ("The value of height %u is too small. I setting this to   %u \n"),
            height, MIN_SIZE;
        height = MIN_SIZE;
    }
    for (unsigned int i = 0; i < width; ++i)
    {
        printf("*");
    }
    return 0;
}

When I give a width of 7 for example, and a height of 0, the printf() presents weird numbers. Can you explain please why this is happening?

Upvotes: 1

Views: 257

Answers (1)

Manoj Pandey
Manoj Pandey

Reputation: 4666

THis one would probably compile with a warning. You need to keep the closing parenthesis after providing all the argument.

printf
            ("The value of height %u is too small. I setting this to   %u \n"),
            height, MIN_SIZE;

Probably you meant:

printf("The value of height %u is too small. I setting this to   %u \n", height, MIN_SIZE);

The main issue is that we should use "%hu" for short intergers. I would try this:

#include<stdio.h>
int main(void)
{
    unsigned short height = 0;
    unsigned short width = 0;
    const unsigned short MIN_SIZE = 3;
    int i ;
    printf("Enter the values for the width and the height minimum of %u\n:", MIN_SIZE);
    scanf(" %hu %hu", &width, &height);
    if (width < MIN_SIZE) {
        printf("The value of width   %hu is too small. I set this to %hu    \n", width, MIN_SIZE);
        width = MIN_SIZE;
    }
    if (height < MIN_SIZE) {
        printf("The value of height %hu is too small. I setting this to %hu \n", height, MIN_SIZE);
        height = MIN_SIZE;
    }
    for (i = 0; i < width; ++i)
    {
        printf("*");
    }
    return 0;
}

There was a good related discussion on SO about this: What is the format specifier for unsigned short int?

Upvotes: 6

Related Questions