dimanche 17 octobre 2021

C++ - If the user inputs multiple characters when I want an integer, it loops through asking them to enter the correct value multiple times

This is my code

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int currency = 0;

    string USD = "USD";
    string EUR = "EUR";
    string JPY = "JPY";
    string GBP = "GBP";
    string CHF = "CHF";
    string CAD = "CAD";
    string AUD = "AUD";
    string ZAR = "ZAR";


    cout << "***Currency Converter***\n\n";

    do 
        {

        cout << "Select initial currency\n";

        cout << "1. " << USD << "\n";
        cout << "2. " << EUR << "\n";
        cout << "3. " << JPY << "\n";
        cout << "4. " << GBP << "\n";
        cout << "5. " << CHF << "\n";
        cout << "6. " << CAD << "\n";
        cout << "7. " << AUD << "\n";
        cout << "8. " << ZAR << "\n";

        cin >> currency;

        if (currency <= 0 || currency >= 9) {
            cout << "Please enter a valid input\n";
            cin.clear();
            cin.ignore();
            cin >> currency;
        }

    } while (currency <= 0 || currency >= 9);

    if (currency == 1) {
        cout << "You've selected USD\n";
    }
    else if (currency == 2) {
        cout << "You've selected EUR\n";
    }
    else if (currency == 3) {
        cout << "You've selected JPY\n";
    }
    else if (currency == 4) {
        cout << "You've selected GBP\n";
    }
    else if (currency == 5) {
        cout << "You've selected CHF\n";
    }
    else if (currency == 6) {
        cout << "You've selected CAD\n";
    }
    else if (currency == 7) {
        cout << "You've selected AUD\n";
    }
    else if (currency == 8) {
        cout << "You've selected ZAR\n";
    }

When I run the program it correctly re-asks the user for a valid input, so long as that input is just the wrong number. However, when the user inputs a string input, it asks the user for the correct input equal to the number of characters within the string. I know the issue is within the loop somewhere, but I don't know where. Thanks for the help.

Aucun commentaire:

Enregistrer un commentaire