cheroky
cheroky

Reputation: 757

Inconvenient to validate negative number

I have this code

    int n;
    char c;

    while ((scanf("%d%c", &n, &c) != 2)|| c != '\n' && n >= 0)
    {
        while( getchar() != '\n' );
    }

I do not understand why does not detect if the input is a negative number, I just want to read positive numbers

Someone sees the problem?

Upvotes: 1

Views: 49

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

Change the condition the following way

while ( (scanf("%d%c", &n, &c) != 2) || c != '\n' || n < 0)

Upvotes: 2

Related Questions