Is there a way to make it so that if user inputs a letter into int hours it will run the else statement and not the else if statement

Viewed 27

The code works the problem is that when a user puts in a letter instead of int into the hours variable the program still runs the else if statement even though that statement is only checking to see if hours>0 and less than 10. How would I fix this problem so that if a user puts in a letter it runs the else statement which is hours input is invalid?

    // RUNS IF PACKAGE = A
    if(package=='A')
    {
        // SETS MONEY TO 9.95
         money = 9.95;
        // ASKS USER HOW MANY HOURS THEY USED
         cout<<"How many hours did the customer use last month?";
            // USER INPUTS HOURS
         cin>>hours;                    
         cout<<""<<endl;
        if(hours>=10 && hours<=744)
        {
            // ISOLATES THE EXTRA HOURS THE USER IS USING           
            hours-=10;                    
            // CALCULATES THE TOTAL MONTHLY CHARGES
            money+=2*hours;             
            // PRINTS MONTHLY CHARGES   
            cout<<"The monthly charges are $"<<money<<endl<<endl;
        
            if(money>14.95)
            {
                // CALCULATES SAVINGS FOR PACKAGE B
                savings=14.95+hours-9.95;         
                // PRINTS THE SAVINGS
                cout<<"By switching to Package B you would save $"<<savings<<endl<<endl;
                // RECALCULATES IT FOR PACKAGE C
                savings =money-19.95;   
                // PRINTS SAVINGS FOR PACKAGE C
                cout<<"By switching to Package C you would save $"<<savings<<endl<<endl;
            } 
        }
        
        else if(hours>=0 &&hours<10)// RUNS THIS STATEMENT IF HOURS>0 AND HOURS < 10
                    {
                            // PRINTS MONTHLY CHARGES
             cout<<"The monthly charges are $"<<money<<endl<<endl;
                    }
        
        else
        {
            // IF NO OTHER CONDITION IS VALID THIS ONE IS PRINTED
             cout<<"Hours input invalid"<<endl<<endl;
        }

        
1 Answers

You can use a simple while loop for integer input validation instead of the simple input statement that you're using.

std::cout << "How many hours did the customer use last month?" << std::endl;
while(!(std::cin >> hours)) //  Iterates until a valid integer is entered.
{

    std::cout << "Invalid input, try again!" << std::endl;
    std::cout << "Hours:" << std::endl;
    std::cin.clear();   //  Clears the input stream.
    std::cin.ignore(100, '\n'); //  Ignores the subsequent 100 characters or until a newline is encountered.

}

Of course, there are many other methods of integer input validation, but this is one that's pretty straightforward and simple to understand.

Related