vendredi 10 août 2018

How do I prevent program from running BOTH an IF and ELSE statement with C++?

#include <iostream>
#include <string>

int main()
{
    int hun;
    std::cout << "Please pick a number between 1 and 100 \n";
    std::cin >> hun;
    if (hun > 50)
    {
        std::cout << "Your number is greater than 50. ";
    }
    if (hun < 50)
    {
        std::cout << "Your number is less than 50. ";
    }
    if (hun > 100) 
    {
        std::cout << "Pick a number LESS than 100. ";
    }
    else { std::cout << "Your number is equal to 50. "; }

    return 0;
}

If I run it without the:

std::cout << "Pick a number LESS than 100. ";

then the program works as expected. However it doesn't work if I include it. For example if I input "13" I get both the message "Your number is less than 50, AND your number is equal to 50" ?? I don't understand why it is still executing the else statement if my IF statement was already met. This isn't an issue ONLY if I removes that 3rd IF statement.

I cannot figure out why it is just that line that is messing up. I seem to have everything written correctly, and I didn't forget the curly brackets. So why is this happening?

I'm sure it's a simple mistake. It's my first week coding and I'm doing it on my own with no outside help, so I don't have anyone to go to for silly questions like this.

While I'm here, how do I get the program to say something like "You have entered an invalid response. " When the user inputs a word or a letter? I thought about doing something like:

int word;
word = 1-100;
if (hun = word) or (hun != int?)

(But that will only subtract 100 from 1 giving me -99 and not the range, I really do not even know where to begin with this)

Aucun commentaire:

Enregistrer un commentaire