TwentyCharMax
TwentyCharMax

Reputation: 123

What's up with this when I put a letter in the console?

So I am using

#include <stdio.h>
int main()
{
    while(true){
        int n, c, k, space = 1;
        printf("pick a number between 1 and 25\n");
        scanf("%d", &n);
        space = n - 1;
        for (k = 1; k <= n; k++) {
            for (c = 1; c <= space; c++)
               printf(" ");
            space--;
            for (c = 1; c <= 2*k-1; c++)
               printf("*");
            printf("\n");
        }
        space = 1;
        for (k = 1; k <= n - 1; k++)
        {
            for (c = 1; c <= space; c++)
                printf(" ");
            space++;
            for (c = 1 ; c <= 2*(n-k)-1; c++)
               printf("*");
            printf("\n");
        }
    }
}

The program works just fine, when you input a number. But when you input a letter it does this

pick a number between 1 and 25
pick a number between 1 and 25
pick a number between 1 and 25

And it does that until you quit the application.

Now, I know this is due to while(true) but why does it output that? Is this specific to a certain processor?

EDIT: you must input a letter first to Re-Produce the problem

Upvotes: 0

Views: 63

Answers (2)

ameyCU
ameyCU

Reputation: 16607

First of all I don't see any statement to break out of while(true) . And when you enter a character -

scanf("%d", &n); 

character does not matches to %d specifier and is left in stdin. And thus , in next iterations same process happens. Entered character remains in stdin and every time scanf read it and ignores it. This leads to an infinite loop.

This behaviour is of scanf and does not depend on compile.

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490108

This behavior is standard across processors and implementations of C (and C++).

The problem is that you've entered a letter where it expected to find a digit. Since it didn't find a digit, it leaves the letter in an input queue, and the attempt at reading the number fails. Then you repeat the same again. You haven't done anything to remove the letter, so it attempts to read a number again, and (of course) fails again.

Essentially any and all the time you read input, you want to check whether reading succeeded. Since you're using scanf, you can check its return value. It returns the number of items it read successfully, so in this case you might do something like this:

printf("Please pick a number between 1 and 25");
if (scanf("%d", &number) == 1)
    // we got a number
else
    // bad input.

In the "bad input" case, you typically want to read characters from the input until you get to a new-line, then make another attempt at reading a number.

Upvotes: 3

Related Questions