KThund
KThund

Reputation: 49

Input validation using C

I'm writing a program to prompt the user to enter a number between 1 and 5. If the value is greater than 5 or less than 1 I want the program to wait until an appropriate answer is given. This is what I came up with and it's not working. I've tried a few different tips off the net and it still isn't working. Any tips would be great, thanks.

#include <stdio.h>

int main()
{
    int p1_move;

    do{                         
        printf("1  \n 2 \n 3 \n 4 \n 5\n");
        printf("Player 1, enter the number:\n");
        scanf("%d", &p1_move);
    }while(p1_move >=6 || <=0);         
}

Upvotes: 0

Views: 118

Answers (2)

paddy
paddy

Reputation: 63471

You need a variable for each test:

while(p1_move >=6 || p1_move <=0);

You also have potentially undefined behaviour here:

scanf("%d", &p1_move);

You do not test whether the input was successful. If the input failed first time around (eg EOF or non-integer input), p1_move will remain uninitialised.

Upvotes: 3

Yu Hao
Yu Hao

Reputation: 122383

Your code shouldn't compile.

Change

while(p1_move >=6 || <=0);  

to

while(p1_move >=6 || p1_move <=0);  

Upvotes: 1

Related Questions