0

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);         
}
1
  • while(p1_move >=6 || p1_move <=0); Commented Oct 8, 2013 at 1:49

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Your code shouldn't compile.

Change

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

to

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

4 Comments

Thanks, this worked. Alternatively, would there be a way to make the while statement say anything that ISN'T 1/2/3/4/5? I thought it was !1!2!3!4!5
@KThund Not really, !a results as 0 for all non-zero a, results as 1 for zero. You still need to test them separately like a != 1 && a !=2 && a != 3 etc.
Sorry, I don't understand. I was thinking of making it so if any character or number other then 1,2,3,4or5 is entered it will repeat the same prompt. Is it possible to do this?
@KThund I'm not saying the logic is wrong. I'm saying the syntax should be like while (a != 1 && a !=2 && a != 3).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.