Variable not being declared before initializing, but it is?!

I'm working on this program, and when i run it for 'p', 'P', or for a incorrect service code a error message pops up saying that "totalCost is being used without being initialized"
I don't want to change it to switches, case, and breaks now because I've come too far to change it all.
I have that variable right here just below. So whats wrong?

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

int main()
{


int acctCode;
double nightCost;
double totalCost;
double dayCost;
double minsUsed, minsDay, minsNight;
char serviceCode;



cout << "Enter your Account Number: " << endl;
cin >> acctCode;
cout << "Enter your Service Code: " << endl;
cin >> serviceCode;

if (serviceCode =='r' || serviceCode == 'R')
{
cout << "How many minutes have you used: " << endl;
cin >> minsUsed;
if (minsUsed > 50)
{
totalCost = 10 + ((minsUsed-50) * .20);
}
else
{
totalCost = 10;
}
}

else if ( serviceCode == 'p' || serviceCode == 'P')
{
cout << "How many day minutes have you used:" << endl;
cin >> minsDay;
cout << "How many night minutes have you used: " << endl;
cin >> minsNight;

if (minsDay > 75 && minsNight > 100)
{
dayCost = minsDay * .10;
nightCost = ((minsNight-100) * .05);
}

else if (minsDay < 75)
{
dayCost = 0;
}

else if ( minsNight < 100)
{
nightCost = 0;
}
totalCost = 25 + dayCost + nightCost;


}


else
{
cout << "NOOOO \n That was the wrong code!!! \n Try again!" << endl;
}

cout << fixed << setprecision(2) << endl;
cout << "You Owe: " << totalCost << endl;
cout << "Account Number: " << acctCode << endl;
cout << "Service Type: " << serviceCode << endl;


return 0;
}
This all runs even if they've entered an invalid code - so in this case, there is no valid value for total cost.

1
2
3
4
cout << fixed << setprecision(2) << endl;
cout << "You Owe: " << totalCost << endl;
cout << "Account Number: " << acctCode << endl;
cout << "Service Type: " << serviceCode << endl;




What if someone selects P and enters over 75 minutes for day and less than 100 minutes for night? or vice versa - under 75 minutes for day, but more than 100 minutes for night? Just wondering if they're supposed to get a pass on being over on one of the minute types if they're under on the other.
I fixed the 'p' part so its works correctly.
What do you suggest to fix this?

cout << fixed << setprecision(2) << endl;
cout << "You Owe: " << totalCost << endl;
cout << "Account Number: " << acctCode << endl;
cout << "Service Type: " << serviceCode << endl;

Wait, I think i just fixed it! I moved the cout statements to the end of each of the two major paths.
I'd probably validate the service code right after they enter it, before starting all the calculations. So if they've entered an invalid code, they can try again.
Topic archived. No new replies allowed.