You are here:

C++/negitive restrictions

Advertisement


Question
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?

Thanks,
~Onion

Answer
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;
do
{
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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

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 ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

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.

©2016 About.com. All rights reserved.