• 0

c++ input validation


Question

I need to do a program that uses two overloaded functions to calculate hospital charges for In Patients and Out Patients. I have it all done and it works right but I need it to have input validation to make it so the user cannot input a negative number.

It doesn't seem to be working now, it still lets you input negative numbers for the in patient and outpatient functions no matter what I try.

I'm a beginner with c++

here's the code so far:

#include<iostream>
#include<iomanip>
using namespace std;

// Function Prototypes
double calcCharges(int, double, double, double, double);
double calcCharges(double, double, double);

int main()
{
   int daysIn = 0;
   double dayRate = 0;
   double medCharges = 0;
   double services = 0;
   double total = 0;
   int patient;

	// Set numeric output formatting.
   cout << fixed << showpoint << setprecision(2);

   // Ask if inpatient or outpatient
   cout << "In Patient(1) or Out Patient (2)" << endl;
   cin >> patient;

   // Call functions
   if (patient == 1)
   	calcCharges(daysIn, dayRate, medCharges, services, total);
   else if (patient == 2)
   	calcCharges(services, medCharges, total);
   else
   	cout << "Invalid input enter (1) or (2)" << endl;


}



// Calculates total for inpatient
double calcCharges(int in, double rate, double med, double serv, double total)
{
	if(in < 0 || rate < 0 || med < 0 || serv < 0)
		cout << "Invalid Input (No Negative Numbers)" << endl;

	else if(in >= 0 || rate >= 0 || med >= 0 || serv >= 0)
	{
		cout << "Days In? " << endl;
   		cin >> in;
   		cout << "Day Rate? " << endl;
   		cin >> rate;
   		cout << "Medical Charges? " << endl;
   		cin >> med;
   		cout << "Services? " << endl;
   		cin >> serv;

   		total = in * rate + (med + serv);
   		cout << "Total: $" << total << endl;
	}

	return total;
}

// Calculates total for out patient
double calcCharges(double serv, double med, double total)
{
	if(serv < 0 || med < 0)
		cout << "Invalid Input (No negative numbers)" << endl;

	else if(serv >= 0 || med >= 0)
	{	
		cout << "Services? " << endl;
   		cin >> serv;
   		cout << "Medical Charges? " << endl;
   		cin >> med;

   		total = serv + med;
   		cout << "Total: $" << total << endl;
	}

	return total;
}

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

What your current code does is verify if the input is valid; execute calcCharges if valid, do nothing if invalid. That's could be a correct form of input validation.

A more user-friendly approach would be to loop the input prompt until the user enters something valid.

input = some_invalid_input
while input is invalid
	prompt for input
	input = read from console

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.