You are here:

C++/negitive restrictions


Im making a "lemonade stand " game for an infotech course. My question is when I enter a number into my game, how do i disallow the user to enter negitive numbers?


Hello Mr. Onion, thank you for the question.

There are a couple of ways you can do this. You could just turn the negative number positive, or you can keep looping until they enter a non-negative number. Here is some psuedo-code:

// in main
// Turn negative input positive
cout << "Enter a positive number: ";
int num;
cin >> num;
if(num < 0)
num = num * -1;

Or, you could loop.
// in main
// loop until valid data is input
int num;
cout << "Enter a positive number: ";
cin >> num;
if(num < 0)
cout << "Number is negative. Please enter a positive number\n";
}while (num < 0);

That way if they provide a negative number, it will print that error message, and then loop another time based on the while conditional statement. When a positive number is entered, it will break from the loop.

I hope this information was helpful.

- Eddie


All Answers

Answers by Expert:

Ask Experts




I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by I also know a good deal about graphics via OpenGL, and GUIs.


I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2017 All rights reserved.

[an error occurred while processing this directive]