ShotYe
ShotYe

Reputation: 13

Is there a simpler way to write this?

Hi I'm learning the basic of C++ and I'm in the process of doing an assignment. I'm asking if there is a simpler way to write this part.

if ( 100 >= projectgrade && 0<= projectgrade ) {}
else 
{
    cout<<endl<<"invalid data, please retry again.";
    cin.ignore();
    cin.get();
    return EXIT_SUCCESS;
}
if ( 100 >= midtermgrade && 0<= midtermgrade ) {}
else 
{
    cout<<endl<<"invalid data, please retry again.";
    cin.ignore();
    cin.get();
    return EXIT_SUCCESS;
}
if ( 100 >= finalexamgrade && 0<= finalexamgrade ) {}
else 
{
    cout<<endl<<"invalid data, please retry again.";
    cin.ignore();
    cin.get();
    return EXIT_SUCCESS;
}

Is it possible to write all those restriction in one bracket of if? I try numerous time but I can't figure it out. Ty for helping out!

Upvotes: 1

Views: 132

Answers (4)

Jarod42
Jarod42

Reputation: 217065

First you may add a function for the test

bool is_valid_grade(int grade)
{
    return 0 <= grade && grade <= 100;
}

or

bool is_valid_grade(unsigned int grade)
{
    return grade <= 100; // unsigned cannot be negative
}

then use it like:

if (is_valid_grade(projectgrade)
    && is_valid_grade(midtermgrade)
    && is_valid_grade(finalexamgrade))
{
    // Valid code
}
else
{
    return failure(); // your previous code into a function
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201399

Well, if you examine your logic it's if any of the grades is less then 0 or greater then 100, so something like this -

if ( projectgrade < 0 || projectgrade > 100 || 
     midtermgrade < 0 || midtermgrade > 100 || 
     finalexamgrade < 0 || finalexamgrade > 100 
   ) {
  cout<<endl<<"invalid data, please retry again.";
  cin.ignore();
  cin.get();
  return EXIT_SUCCESS;
}

Edit and we could always add a #define like

#define range(x) x < 0 || x > 100

then that if could be shortened to

if (range(projectgrade) || range(midtermgrade) || range(finalexamgrade))

Upvotes: 4

M.M
M.M

Reputation: 141534

In C++11 you can write:

auto failure = [](){
    cout << "invalid data, please try again" << endl;
    cin.ignore();
    cin.get();
    return 0;
};

and then use it when failures happen:

if ( !(100 >= projectgrade && 0<= projectgrade) )
   return failure();

// do more stuff

if ( !(100 >= midtermgrade && 0<= midtermgrade) )
    return failure();

Note, doing endl after your text instead of before it is preferable; return 0; always indicates success, and cin.ignore() just ignores a single character (in general, you may want to ignore the rest of the line).

Upvotes: 0

user93353
user93353

Reputation: 14039

if ( (projectgrade <0) || (projectgrade > 100) || (midtermgrade <0) || (midtermgrade > 100) || (finalexamgrade < 0) || (finalexamgrade > 100))
{
    cout<<endl<<"invalid data, please retry again.";
    cin.ignore();
    cin.get();
    return EXIT_SUCCESS;
}

Upvotes: 2

Related Questions