0

I'm trying to code a simple program that prints out stars in the shape of a hill. It works by taking a user input width and printing the number of stars up until the width specified is reached. The main section of code that's printed is finished. However, I'm having issues trying to ensure the inputted number is odd. If the number is even, the function is supposed to continue asking the user to input another number until they input an odd number.

The relevant part of the code:

int rowsinput;

cout << "Enter an odd number width: ";
cin >> rowsinput;

if (rowsinput % 2 == 0)
{
    cout << "Please enter an odd number width: ";
}
else

If anyone needs me to post the entire code please comment.

3 Answers 3

1

you can use something like:

int rowsinput;
do{
  cout << "Enter an odd number width: ";
  cin >> rowsinput; 
}while(rowsinput % 2 == 0)
Sign up to request clarification or add additional context in comments.

1 Comment

Potential infinite loop with input "qwerty" and allows for rowsinput to be used uninitialized.
0

Add cin statement inside while loop as follows:

while(rowsinput % 2 ==0)
{
    cout << "Please enter an odd number width: ";
    cin >> rowsinput;
}

Your final code will be as follows :

cout << "Enter an odd number width: ";
cin >> rowsinput;
while(rowsinput % 2 ==0)
{
    cout << "Please enter an odd number width: ";
    cin >> rowsinput;
}

1 Comment

And what of a second invalid input?
0

Consider as a substitute

while (!(cin >> rowsinput) ||  // bad, non-parsable input
       (rowsinput % 2 == 0) || // even number
       (rowsinput  < 0))       // negative number
{
    cout << "Please enter an odd number width: ";
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin.clear();
}
// input is good. Carry on with rest of program

This will loop until the user provides a valid integer, that integer is odd, and the integer is positive. If any of those conditions is not met, the user is prompted for more input, all current (bad) input is discarded, and any error conditions on the input stream are cleared.

Edit:

Requires an additional #include <limits> to get the numeric limits in the ignore call.

Comments

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.