简体   繁体   中英

Input Validation in C++

I am writing a program that is needing input validation saying that if the units are less than or equal to 0 the program won't run, but I keep getting the string with the total included but I am not trying to run that if the value is 0.

//Write a program that asks for the numbers of units sold and computes the total cost of purchase
//Make sure to use input validation that the number of units is greater        than 0
#include <iostream>
using namespace std;

int main ()
{
    double discount, discountTotal, units, total;
    double package = 99;

    cout << "What is the number of units sold? ";
    cin >> units;
    if(units <=0){
        cout << "Units must be greater than 0" << endl;
    }
    if(units > 0 && units < 10)
        discount = .00;
    else if(units >=10 && units <= 19)
        discount = .20;
    else if(units >=20 && units <= 49)
        discount = .30;
    else if(units >=50 && units <= 99)
        discount = .40;
    else if(units >=100, .50)
        discount = .50;

    discountTotal = package * discount;
    total = package - discountTotal;
    cout << "Your total is: " << total << endl;

    return 0;
}

You can return immediately if the input is not correct:

if(units <=0){
    cout << "Units must be greater than 0" << endl;        
    return -1; // if the input 0 or negative, the program will end here
}

Without that, the following code is always executed:

// ...
discountTotal = package * discount;
total = package - discountTotal;
cout << "Your total is: " << total << endl;
// ...

Related: What should main() return in C and C++?

Mmm... I think that would be better:

#include <iostream>
using namespace std;

int main ()
{

    double discount, discountTotal, units, total;
    double package = 99;

    cout << "What is the number of units sold? ";
    cin >> units;

    if(units <=0)
    {
        cout << "Units must be greater than 0" << endl;
    }
    else
    {
        if(units > 0 && units < 10)
            discount = .00;
        else if(units >=10 && units <= 19)
            discount = .20;
        else if(units >=20 && units <= 49)
            discount = .30;
        else if(units >=50 && units <= 99)
            discount = .40;
        else if(units >=100, .50)
            discount = .50;

        discountTotal = package * discount;
        total = package - discountTotal;
        cout << "Your total is: " << total << endl;
    }
    return 0;
}

And you were outputting the total no matter what the user enter... Hope it help!

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