简体   繁体   中英

Validating input values with an if/else statement in C++

So I've looked around but I'm apparently either not looking in the right place or I'm misunderstanding something.

The directions given are that the program can only accept values between 2.0 and 5.0 for vault heights. I get the feeling it has to do with my if condition but I'm not sure how to correct it.

When I input the height during debugging, it jumps to my else statement, and doesn't give me a chance to re-enter the new input.

//Retrieving name and first vault and date
cout << "Please enter the name of the pole vaulter.\n";
getline(cin, name);
cout << "Please enter the height of the first vault attempt.\n";
cin >> vault1;
if(5.0 >= vault1 >= 2.0) {
    cout << "What date was this vault accomplished?\n";
    getline(cin, date1);
} else {
    cout << "Only jumps between 2.0 meters and 5.0 meters are valid inputs.       Please enter the height of the first vault attempt.\n";
    cin >> vault1;
    cout << "What date was this vault accomplished?\n";
    getline(cin, date1);
}

The expression

5.0>=vault1>=2.0

should work fine in Python, but in C++ it's parsed as

(5.0>=vault1) >= 2.0

where the result of the first comparison is compared to 2.0, yielding a nonsense result.

In C++ write that instead as

2.0 <= vault1 && vault1 <= 5.0

If you perform this check in more than one place, then it can help on clarity and maintainability define a suitably named boolean function.

C++ doesn't support mathematical expression.

Change:

if (5.0>=vault1>=2.0)

To:

if (vault1 > 5.0 || valut1 < 2.0)
{
   // invalid vault1
}
else
{
   // valid vault1
}

OR if you want to use &&

if (vault1 <= 5.0 && valut1 > 2.0)
{
   // valid vault1
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM