0

I am trying to make it so if the user enters a number less than 4 or greater them 10 they are prompted it is invalid and to enter a new number. the problem I am having is if they do enter a proper number it does not continue on to the next part. Here is what I have so far:

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
#include <ctime>

int NewRandomNumber (int n);
void MakeQuestion (int n, int& a, int& b, int& atimesb);
bool UserAnswer (int a, int b, int atimesb);
void PrintScore (int numCorrect, int numAsked);

using namespace std;

int main()

{
string name;
int n;
string s;




cout << "Welcome to Multiplication Quiz 1000!" << endl;
cout << "Firstly what is your name?\n" << endl;

cin >> name;

cout << "\nHi " << name <<" !" << endl;
cout << "What difficulty would you like your quiz to be? Enter a value from [4 to 12]

      \nwith 4 being the easiest:\n" << endl;

do
{
cin >> s;
n = atoi(s.c_str());

if ( n >= 4 || n <= 10)



  if ( n < 4 || n > 10)
    {cout << "invalid. try again" << endl;
    }



{cout << "Ok" << endl;
cout << NewRandomNumber (4);
}

}
while ( n >= 4 || n <= 10);


 return 0;

 }

int NewRandomNumber (int n)

{ 

    n = rand()% 10 + 1;




return (n);

 }

void MakeQuestion (int n, int& a, int& b, int& atimesb)

{
}
1
  • use getline instead to read from the keyboard getline(cin,s); Commented Aug 15, 2013 at 12:28

3 Answers 3

4

Your while( n >= 4 || n <= 10) condition will always be true. You should go with while (n <= 4 || n >= 10).

There are a few ways to solve your problem, like it was already posted here. I would go with a continue statement, like slacker said, but be sure to change your while condition, otherwise it won`t work. It would be something like this:

while (true) {
    cin >> s;
    n = atoi(s.c_str());

    if (n <= 4 || n >= 10) {  
    // handles your exception and goes back to the beggining of the loop
    continue;
    }
    else {
    // the number was correct, so make your magic happen and then...
    break;
    }
} 
Sign up to request clarification or add additional context in comments.

Comments

1

I think you miss continue statement.

:

// .............

        if ( n < 4 || n > 10)
            {cout << "invalid. try again" << endl;
             continue;
            }

    //..............

Comments

1

Try it this way by using a flag:

int flag=0;

do{

cin >> s;
n = atoi(s.c_str());


if ( n < 4 || n > 10)
{
  cout << "invalid. try again";
}
else
{
   flag=1;
   cout<<"OK"
}
}while(flag=0);

It has been quite a while since I have programmed in C++, so there may be some minor problems with syntax. But logic here should be fine.

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.