C++ How to add the sum from values in multiple if statements - c++

I'm having an issue in gathering and printing the total the sum(totalPrice) in my program.
The program repeatedly asks the user to enter ticket information and then calculates the total price for all the tickets entered.
If a ticket is requested to some other destination, the program informs the user that no tickets are available to that destination. The user can enter the city names as given or in all lower case.
The round trip price is the one-way price multiplied by 1.6. There is a 20% discount for students.
When the user enters the word “Done” or “done” when asked for the destination, the program outputs the total number of tickets and their total price and exits.
Everything is working fine as far as I know, except the final output of for total cost. Any help guys as to what I'm doing. I believe it might be my logic, but I'm too invested to see my mistake! Any help will be appreciated, thank you :)
using namespace std;
int main() {
double totalPrice = 0; // the sum of all the values after the do while loop is done.
int numberOfTicketsSold; // ehhhh counter?
int counter; // keep track of the number of flights
double temp = 0; // to hold the values while they're being adjusted
double discount = 0; // another temp but for discount
double boston = 350; // constant at 350 per trip
double london = 600;
double paris = 700;
double tokyo = 800;
string input; // might have to use char instead. Lets try it out anyways.
string roundTrip;
string studentDiscount;
cout << "**************************************************************" << endl;
cout << "Enter the information for each ticket." << endl;
cout << "When no more tickets to enter, enter 'Done' for destination." << endl;
cout << "**************************************************************" << endl;
do{
cout << "Enter the destination city:" ; // Want to collect the string inputted to start if statements
cin >> input;
if ( input == "boston" || input == "Boston")
{
counter++; // keeps track of how many flights. For last output
cout << "\nRound trip? [Y/N]" << endl;
cin >> roundTrip;
if (roundTrip == "y" || roundTrip == "Y")
{
temp = boston;
temp = temp * 1.6;
}
else if(roundTrip == "n" || roundTrip == "N")
{
temp = boston;
}
cout << "\nStudent Discount? [Y/N]";
cin >> studentDiscount;
if (studentDiscount == "y" || studentDiscount == "Y")
{
discount = temp;
discount = discount *.20;
temp = temp - discount;
totalPrice = temp;
}
else if(studentDiscount == "N" || studentDiscount == "n")
{
totalPrice = temp;// do nothing right?
}
}
else if ( input == "london" || input == "London")
{
counter++; // keeps track of how many flights. For last output
cout << "\nRound trip? [Y/N]" << endl;
cin >> roundTrip;
if (roundTrip == "y" || roundTrip == "Y")
{
temp = london;
temp = temp * 1.6;
}
else if(roundTrip == "n" || roundTrip == "N")
{
temp = london;
}
cout << "\nStudent Discount? [Y/N]";
cin >> studentDiscount;
if (studentDiscount == "y" || studentDiscount == "Y")
{
discount = temp; // 600
discount = discount *.20;
temp = temp - discount;
totalPrice = totalPrice + temp;
}
else if(studentDiscount == "N" || studentDiscount == "n")
{
totalPrice = totalPrice + temp;// do nothing right?
}
}
else if ( input == "paris" || input == "Paris")
{
counter++; // keeps track of how many flights. For last output
cout << "\nRound trip? [Y/N]" << endl;
cin >> roundTrip;
if (roundTrip == "y" || roundTrip == "Y")
{
temp = paris;
temp = temp * 1.6;
}
else if(roundTrip == "n" || roundTrip == "N")
{
temp = paris;
}
cout << "\nStudent Discount? [Y/N]";
cin >> studentDiscount;
if (studentDiscount == "y" || studentDiscount == "Y")
{
discount = temp;
discount = discount *.20;
temp = temp - discount;
totalPrice = temp;
}
else if(studentDiscount == "N" || studentDiscount == "n")
{
totalPrice = temp;// do nothing right?
}
}
else if ( input == "tokyo" || input == "Tokyo")
{
counter++; // keeps track of how many flights. For last output
cout << "\nRound trip? [Y/N]" << endl;
cin >> roundTrip;
if (roundTrip == "y" || roundTrip == "Y")
{
temp = tokyo;
temp = temp * 1.6;
}
else if(roundTrip == "n" || roundTrip == "N")
{
temp = tokyo;
}
cout << "\nStudent Discount? [Y/N]";
cin >> studentDiscount;
if (studentDiscount == "y" || studentDiscount == "Y")
{
discount = temp;
discount = discount *.20;
temp = temp - discount;
totalPrice = temp;
}
else if(studentDiscount == "N" || studentDiscount == "n")
{
totalPrice = temp;// do nothing right?
}
}
} while (input != "done");
cout << "--------------------------------------------------------------"<< endl;
cout << counter << " tickets sold for a total sum of $" << temp << endl;
cout << "-------------------------------------------------------------";
}

Related

How to check if date format(dd/mm/yyyy) is correct in C++?

I have made a program that sort dates and displays them year-wise. 0+years, 10+years, 20+years, etc. I have also validated the date. For example, there should be no more than 31 or less than 1 days. I also have validation for leap years, months etc. How do I check if format of date is valid or not? I want to should show an error message that the date format is incorrect on inputting date as 6/7/2008 or 6/07/2008. The format should be dd/mm/yyyy.
Person People::getPerson()
{
Person person;
Validation validate;
string input;
bool ch;
int memNo = 0;
cout << " \nEnter another Person\n" << "Membership Number: ";
cin >> memNo;
person.SetMemNo(memNo);
//While the input entered is not an integer, prompt the user to enter an integer.
while(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<int>::max(), '\n');
cout << "Invalid data. Please type an integer! " << endl;
cout << "Membership Number: ";
cin >> memNo;
cout << endl;
}
cout << "Enter first name of person: ";
cin >> input;
bool onlystring = validate.IsDigitsOnly(input);
//validate string for only alphabets,no numbers
if (onlystring == true) {
cout << "Enter only alphabets for first name" << endl;
cout << "Enter first name of person: ";
cin.clear();
cin.ignore();
cin >> input;
}
person.SetFirstName(input);
cout << "Enter your Surname ";
cin >> input;
person.SetLastName(input);
bool onlystring1 = validate.IsDigitsOnly(input); //validate string for only alphabets,no numbers
if (onlystring1 == true) {
cout << "Enter only alphabets for last name" << endl;
cout << "Enter your Surname ";
cin >> input;
}
bool valid_date = false;
do {
cout << "Enter your date of joining(DD/MM/YYYY): ";
cin >> input;
string new_date= validate.checkFormat(input);
valid_date = validate.valDate(new_date);
if (valid_date == true)
person.SetDateJoined(new_date);
else
cout << "Invalid Date!Please re-enter date of joining!" << endl;
} while(valid_date == false);
date validation
bool Validation::valDate(string input)
{
int Y = stoi(input.substr(6));
int M = stoi(input.substr(3, 2));
int D = stoi(input.substr(0, 2));
//check year
if (Y >= 1900 && Y <= 9999)
{
//check month
if (M >= 1 && M <= 12)
{
//check days
if ((D >= 1 && D <= 31) && (M == 1 || M == 3 || M == 5 || M == 7 || M == 8 || M == 10 || M == 12)) {
return true;
}
else if ((D >= 1 && D <= 30) && (M == 4 || M == 6 || M == 9 || M == 11)) {
return true;
}
else if ((D >= 1 && D <= 28) && (M == 2)) {
return true;
}
else if (D == 29 && M == 2 && (Y % 400 == 0 || (Y % 4 == 0 && Y % 100 != 0))) {
return true;
}
else {
return false;
}
}
else
{
return false;
}
}
else
{
printf("Year is not valid.\n");
return false;
}
return 0;
}
int Validation::Prepend_function ( int n) {
if (n < 10 && n < 0) {
string num = to_string(n);
string new_num = "0" + num;
int number = stoi(new_num);
return number;
}
else {
return n;
}
}
string Validation::checkFormat(string input)
{
//check the length of the string
int len = input.size();
if (len != 10)
{
int year = stoi(input.substr(4));
int month = stoi(input.substr(2, 1));
int day = stoi(input.substr(0, 1));
int prepend_day = Prepend_function(day);
int prepend_month = Prepend_function(month);
string day1 = to_string(prepend_day);
string month1 = to_string(prepend_month);
string year1 = to_string(year);
string date = day1+"/"+month1+"/"+year1;
return date;
}
}
I think you are asking how to implement Validation::checkFormat, because Validation::valDate doesn't seem incorrect.
std::string Validation::checkFormat(std::string input)
{
std::stringstream in(input);
int day, month, year;
char ignore;
// Match num/num/num, otherwise invalid
if (in >> day >> ignore >> month >> ignore >> year)
{
std::stringstream out;
// Force leading 0s
out << std::setfill('0') << std::setw(2) << day << '/' << month << '/' << std::setw(4) << year;
return out.str();
}
// have to return something if it isn't valid
return std::string();
}
Note that checkFormat sounds to be the wrong name for returning a string formatted in a particular way. I would call it fixFormat, and compare input to the result of fixFormat. If they are the same, then input is in the specified format

Program to calculate difference between two times for "time travel"

I am writing a "time travel" program which is supposed to ask the user for the current time, their target travel time, relay those values to be converted into minutes in a function and then based on if the time difference is too high it will not allow the time travel or if it is allowed it will print if they are in the future or the past. My issue right now is that the current time, which is only supposed to be relevant the first iteration, or the first "jump" of the program is not being updated after the jump occurs, and the program defaults to it instead of the target time, which is supposed to be the technical "current time" after the jump has occurred. I have been trying to figure this out for hours and I can't, so I am hoping someone could help me out.
Thank you for your time
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int compute_time_difference(int c_hrs, int c_mins, bool c_am, int t_hrs, int t_mins, bool t_am);
void print_future();
void print_past();
void print_SecurityProtocol();
int main()
{
int c_hrs, c_mins;
int t_hrs, t_mins;
int system_time2;
int time_difference2;
bool c_am = 0;
bool t_am = 0;
char c, c2, Y, N, y, n, jumpAgain;
string am_or_pm_current, am_or_pm_target;
bool g_stop = true;
cout << "Welcome to Po Sled" << endl;
cout << "\tSystem booting..." << endl;
for (int i = 0; i<1; i++) //for loop to run once
{
cout << "\n\tEnter current time below: " << endl;
cout << "\t>Enter hour: "; //User inputs current time in hours
cin >> c_hrs;
while (c_hrs > 12 || c_hrs < 1)
{
cout << "Error: Please enter an hour in the range [1, 12]: ";
cin >> c_hrs;
}
cout << "\t>Enter minutes: "; //User inputs current time in minutes
cin >> c_mins;
while (c_mins > 59 || c_mins < 0) {
cout << "Error: Please enter minutes in the range [0, 59]: ";
cin >> c_mins;
}
cout << "\t>Is it AM or PM?: "; //Classifying if current time is AM or PM
cin >> am_or_pm_current;
while (am_or_pm_current != "am" && am_or_pm_current != "AM" && am_or_pm_current != "pm" && am_or_pm_current != "PM") { //Checks if valid input, if not repeats message until valid
cout << "\tError: Please enter AM/am or PM/pm: ";
cin >> am_or_pm_current;
}
if ((am_or_pm_current == "am") || (am_or_pm_current == "AM"))
{
c_am = 1;
}
else if ((am_or_pm_current == "pm") || (am_or_pm_current == "PM"))
{
c_am = 0;
}
cout << "\n\tCurrent system time set to " << c_hrs << ":" << setw(2) << setfill('0') << c_mins << am_or_pm_current << endl;
cout << "\n\t\tIs this time correct (Y or N)? ";
cin >> c;
while (c != 'Y' && c != 'y' && c != 'n' && c != 'N')
{
cout << "\t\t\tError: Please enter Y/y or N/n: ";
cin >> c;
}
if (c == 'N' || c == 'n')
{
continue;
}
else
{
cout << "\n\tSystem initializing and TARDIS unit warming...." << endl;
cout << "\tThe Po Sled is engaged and ready for input." << endl;
}
}
do {
//Starts a loop for target jump
cout << "\n\tEnter target time below: " << endl; //Enters target time of jump
cout << "\t>Enter Hour: ";
cin >> t_hrs;
while (t_hrs > 12 || t_hrs < 1) {
cout << "Error: Please enter an hour in the range [1, 12]: ";
cin >> t_hrs;
}
cout << "\t>Enter minutes: ";
cin >> t_mins;
while (t_mins > 59 || t_mins < 0) {
cout << "\tError: Please enter minutes in the range [0, 59]: ";
cin >> t_mins;
}
cout << "\n\tIs it AM or PM?: ";
cin >> am_or_pm_target; //Classifying if target time is AM or PM
while (am_or_pm_current != "am" && am_or_pm_current != "AM" && am_or_pm_current != "pm" && am_or_pm_current != "PM")
{ //Validates input is AM or PM
cout << "\tError: Please enter AM/am or PM/pm: ";
cin >> am_or_pm_target;
}
if ((am_or_pm_target == "am") || (am_or_pm_target == "AM"))
{
t_am = 1;
}
else if ((am_or_pm_target == "pm") || (am_or_pm_target == "PM"))
{
t_am = 0;
}
cout << "\tTarget time set to " << t_hrs << ":" << setw(2) << setfill('0') << t_mins << am_or_pm_target; //Sets target time
cout << "\n\t\tIs this time correct (Y or N)? "; //Validates if target time entered is correct
cin >> c2;
while (c2 != 'Y' && c2 != 'y' && c2 != 'n' && c2 != 'N')
{
cout << "\t\t\tError: Please enter Y/y or N/n: ";
cin >> c2;
}
time_difference2 = compute_time_difference(c_hrs, c_mins, c_am, t_hrs, t_mins, t_am);
if (time_difference2 > 360) //If time difference is greater than 6 hours prints error function
{
print_SecurityProtocol();
continue;
}
if (c2 == 'N' || c2 == 'n')
{
continue;
}
cout << "\tJump was made, the current time is " << t_hrs << ":" << setw(2) << setfill('0') << t_mins << am_or_pm_target << endl;
if (time_difference2 < 0 && time_difference2 > -360) //If time difference is less than 0 prints past function
{
print_past();
}
else if (time_difference2 >= 0 && time_difference2 <= 360) //If time difference is ahead of current time prints future function
{
print_future();
}
cout << "\tWould you like to jump again (Y/N)? ";
cin >> jumpAgain;
while (jumpAgain != 'Y' && jumpAgain != 'y' && jumpAgain != 'n' && jumpAgain != 'N') //Input validation
{
cout << "\t\t\tError: Please enter Y/y or N/n: ";
cin >> jumpAgain;
}
if (jumpAgain == 'n' || jumpAgain == 'N') //User exiting program
{
if (time_difference2 < 0)
{
cout << "\t\tSystem shutting down; enjoy the past.\n" << endl;
}
else if (time_difference2 >= 0 && time_difference2 < 360)
{
cout << "\t\tSystem shutting down; enjoy the future.\n" << endl;
}
}
if (jumpAgain == 'Y' || jumpAgain == 'y')
{
continue;
}
} while (jumpAgain != 'n' && jumpAgain != 'N');
return 0;
}
int compute_time_difference(int c_hrs, int c_mins, bool c_am, int t_hrs, int t_mins, bool t_am) //Computes time differences.
{
int currentTime_hours, currentTime_minutes, targetTime_hours, targetTime_minutes, currentTime, targetTime;
int time_difference;
if (c_am == 1) //if c_am is true and it is morning
{
if (c_hrs == 12)
{
currentTime_hours = c_hrs * 0;
}
else if (c_hrs != 12)
{
currentTime_hours = (c_hrs * 60);
currentTime_minutes = c_mins;
currentTime = currentTime_hours + currentTime_minutes; //Sets the value of the current time
}
}
else if (c_am == 0) //if c_am is false and it is afternoon time
{
if (currentTime_hours == 12)
{
c_hrs = c_hrs * 60;
}
else if (currentTime_hours != 12)
{
currentTime_hours = ((c_hrs + 12) * 60);
currentTime_minutes = c_mins;
currentTime = currentTime_hours + currentTime_minutes; //Sets the value of the current time
}
}
if (t_am == 1) //if t_am is true and it is morning time
{
if (targetTime_hours == 12) //if target hours equal to 12 special math
{
targetTime_hours = t_hrs*0;
}
else if (targetTime_hours != 12) //else do this math
{
targetTime_hours = ((t_hrs) * 60);
targetTime_minutes = t_mins;
targetTime = targetTime_hours + targetTime_minutes;
}
}
else if (t_am == 0) //if target time equal to pm then do this math
{
if (targetTime_hours == 12)
{
targetTime_hours = t_hrs * 60;
}
else if (targetTime_hours != 12) //else if target time not equal to 12 then do normal pm math
{
targetTime_hours = ((t_hrs + 12) * 60);
targetTime_minutes = t_mins;
targetTime = targetTime_hours + targetTime_minutes;
}
}
time_difference = targetTime - currentTime;
cout << "the difference computed is " << time_difference;
return time_difference;
}
void print_SecurityProtocol() //Function which prints security protocol error message
{
cout << "\tSecurity Protocols Engaging" << endl;
cout << "\t\tError: The time difference is greater than 6 hours." << endl;
cout << "\t\t\tPlease re-enter target time." << endl;
}
void print_past() //Function that prints when a user is in the past
{
cout << "\tHold onto your lower posterior regions" << endl;
cout << "\n\t\tYou are now in the relative past" << endl;
}
void print_future() //Function that prints when a user is in the future
{
cout << "\tHold onto your lower posterior regions" << endl;
cout << "\n\t\tYou are now in the relative future " << endl;
}
Why do you not use a system time call, instead of getting user input for the 'current time'? Also, use a 24-hour clock instead of a 12-hour and you have removed the need to cater for am/pm within your process.
AM n ot much of a coder but c_hrs*60 would be (at least) 60 hours and (at most) 24*60 which, with the exception of a drive across Europe, Russia, Australia or the Northern US would be excessive time recording. Do you not mean to refer to MINUTES instead of hours (c_mins*60)?

Need help creating an equation in C++ to calculate total

My updated code. When I run the code it keeps outputting the prices of all the packages instead of just the one I ask for.
#include <iostream>
using namespace std;
int main() {
// to keep it simple
int choice_a = 995;
int choice_b = 1995;
int choice_c = 3995;
char choice;
int message_units, x=1;
double price;
bool selected = false;
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice;
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
do{
cout << "How many message units (enter 1 - 672)" << endl;
// again check this
cin >> message_units;
x++;
}
while(x<2);
if(message_units > 5){
choice_a += 100 * (message_units - 5);
}
cout << "Your total cost is " << choice_a /100 << "." <<choice_a%100 endl
if(message_units > 15){
choice_b += 50 * (message_units - 15);
}
cout <<"Yourtotalcostis"<<choice_b /100 << "." << choice_b%100<<endl;
(You missed an "i" or two, but English is difficult for a non-native speaker.)
Atotalcost = 9.95;
if(messageunits>5)
Atotalcost += 1.0 * (messageunits-5);
EDIT:
There are several ways to deal with amounts of money. One of them is to store an amount as a number of cents, then print it out with care. For example, the amount $2.34 is stored as int price = 234, then to print it out we print price/100 (which is 2), then a decimal point, then price%100 (which is 34, the '%' is the modulo operator, you can look it up). So the code will look like this:
#include <iostream>
using namespace std;
int main()
{
int messageunits;
cout << "how many message units(enter 1 - 672)" << endl;
cin >> messageunits;
int Atotalcost = 995; // cost of package a, in cents
if(messageunits > 5){
Atotalcost += 100 * (messageunits - 5);
}
cout << "Your total cost is " << Atotalcost/100 << "." << Atotalcost%100 << endl;
}
There is still much work to do, but this is a good start.
Along those lines, this example may have a few minor errors and I tried to keep it simple.
#include <iostream>
using namespace std;
int main() {
bool finished = false;
do {
// to keep it simple
double choice_a = 9.95;
double choice_b = 19.95;
double choice_c = 39.95;
char choice;
int message_units;
double price;
bool selected = false;
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
// user enters how many units is wanted
cout << "How many message units (enter 1 - 999)" << endl;
// again check this (if homework requires checking input)
cin >> message_units;
// Calculating message units
if (message_units > 5) price += message_units * 1;
else price += message_units * 2; // if $2.00 normal?
// Total Price Output
cout << "Total: " << price << endl;
// Is user done?
char done;
cout << "Do you want to enter another? press enter to continue. If you are done, type something and press enter.";
cin >> done;
// check
if (done != '') {
finished = true;
}
}
while (finished = false);
Alright, that is about it. Two do while loops and the rest. There may be some slight errors while compiling, really, you should try to fix those yourself as this is pretty much the entire assignment...

Trouble executing program that uses both pass by reference and pass by value parameter

I keep getting errors when I try to execute the following program, and I do not know if something is wrong with one of my functions or what(the way I wrote it). I know something is wrong with line 129 in my code, but whenever I try to make changes other syntax errors show up. Basically there is something wrong with my syntax and since I'm learning debugging I'm having a hard time with this.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//declare global functions
void num_units( int& input1 );
void student_fees( float& num1, int& var1 );
void state_resident( bool& cond1 );
char parking_decal( char& ans1 );
void other_student_services_fees( char& ans2, char& ans3 );
int main ()
{
bool not_a_resident = false;
char want_as_sticker = 'x', want_parking_decal = 'y', want_id_card = 'z';
string semester_session = "not enrolled yet";
int units = 0, semester = 0;
float price_per_unit = 0, unit_fees = 0, student_services_fee = 0, parking_decal_fee = 0, total_fees = 0, as_sticker_fee = 19.50, id_card_fee = 13.00;
num_units( units );
student_fees( student_services_fee, semester );
state_resident( not_a_resident );
parking_decal( want_parking_decal );
other_student_services_fees( want_as_sticker, want_id_card );
//determine total student services fee depending on user's preferences
if ( want_as_sticker == 'n' )
student_services_fee = student_services_fee - as_sticker_fee;
if ( want_parking_decal == 'n' )
student_services_fee = student_services_fee - parking_decal_fee;
if ( want_id_card == 'n' )
student_services_fee = student_services_fee - id_card_fee;
//determine price per unit
if ( not_a_resident == false )
price_per_unit = 325.00;
else
price_per_unit = 46.00;
//determine unit_fees
unit_fees = price_per_unit * units;
//determine parking decal price
if ( ( parking_decal( want_parking_decal ) == 'y' ) && ( (semester == 1) || (semester == 3) ))
parking_decal_fee = 45.00;
else
parking_decal_fee = 85.00;
//calculate total fees
total_fees = unit_fees + student_services_fee;
if ( semester == 0 )
semester_session = "Fall";
else if ( semester == 1)
semester_session = "Winter";
else if ( semester == 2)
semester_session = "Spring";
else
semester_session = "Summer";
cout << "For " << semester_session + " " << "your total fees are $ " << total_fees;
return 0;
}
void num_units( int& input1 )
{
cout << "SMC Fee Calculator" << endl;
cout << "Enter number of units enrolled: ";
cin >> input1;
cout << endl;
}
//calculates the unit fees
void student_fees( float& num1, int& var1 )
{
do
{
//determines semester unit price
cout << "Is this Fall[0], Winter[1], Spring[2] or Summer[3] session: ";
cin >> var1;
if ( var1 == 0 || var1 == 2 )
num1 = 50.50;
else if ( semester == 1 || semester == 3 )
num1 = 48.50;
else
cout << endl;
cout << "I'm sorry. That's an improper selection. Please try again.\n";
}while ( var1 <= 4 && var1 >= 0 );
}
void state_resident( bool& cond1 )
{
cout << "Are you a state resident[0] or not[1]: ";
cin >> cond1;
cout << endl;
}
char parking_decal( char& ans1 )
{
do
{
cout << "Want a parking decal? [y/n]: ";
cin >> ans1;
if ( (ans1 != 'y') || (ans1 != 'n') )
cout << "I'm sorry. That's not a valid input. Please try again.\n";
else
break;
}while ( (ans1 != 'y') || (ans1 != 'n') );
cout << endl;
return ans1;
}
void other_studentservices_fees( char& ans2, char& ans3 )
{
//Ask if user wants an AS sticker.
do
{
cout << "Want an AS sticker? [y/n]: ";
cin >> ans2;
//proof answer
if ( (ans2 != 'y') || (ans2 != 'n') )
cout << "I'm sorry. That's not a valid input. Please try again.\n";
else
break;
}
cout << endl;
//Ask if user wants an AS sticker.
do
{
cout << endl << "Want an ID card? [y/n]: ";
cin >>ans3;
//proof answer
if ( (ans2 != 'y') || (ans2 != 'n') )
cout << "I'm sorry. That's not a valid input. Please try again.\n";
else
break;
}
cout << endl;
}
Output should look like this:
SMC Fee Calculator
Enter number of units enrolled: 18
Is this Fall[0], Winter[1], Spring[2] or Summer[3] session: 0
Are you a state resident[0] or not[1]: 0
Want a parking decal? [y/n]: n
Want an AS sticker? [y/n]: n
Want an ID card? [y/n]: n
For Fall semester, your total fees are $ 846.00
SMC Fee Calculator
Enter number of units enrolled: 6
Is this Fall[0], Winter[1], Spring[2] or Summer[3] session: 1
Are you a state resident[0] or not[1]: 1
Want a parking decal? [y/n]: y
Want an AS sticker? [y/n]: y
Want an ID card? [y/n]: y
For Winter semester, your total fees are $ 2043.50
I've looked at your program for 5 min and there are so many errors I'm not even sure where to begin...
Line 131 and 145: You forgot the do-while condition.
Line 141: Should probably replace "ans2" by "ans3" (shitty names for variables by the way)
Line 89: Semester is undeclared, seems like you were supposed to use "var1" instead, which is another horrible name.
Line 12: You declare the function "other_student_services_fees" yet you never define it
At that point I just gave up on you. We are not here to do your homework for you, those are basics errors you could have found yourself.

C++ File editing without deleting.other information

I am programming a stock trading program.
For this function, I need to change the balance in a specific account, but whenever I output back to the file, it updates the balance for one account and deletes everyone else.
Source Code:
void Buying()
{
ifstream Companies;
ifstream Account;
Account.open("Account.txt");
{
int ID;
double cash;
string sym;
ifstream Account;
Account.open("Account.txt");
//Check for errord
if (Account.fail())
{
cout << "Failed" << endl;
exit(1);
}
account S_accounts;
for (int i = 0; i < 5; i++)
{
Account >> S_accounts.id[i] >> S_accounts.cash[i];
}
cout << "Please enter your last 4 digits of your ID: ";
do
{
cin >> ID;
cout << endl;
switch (ID)
{
case 1111:
cash = S_accounts.cash[0];
break;
case 2222:
cash = S_accounts.cash[1];
break;
case 3333:
cash = S_accounts.cash[2];
break;
case 4444:
cash = S_accounts.cash[3];
break;
case 5555:
cash = S_accounts.cash[4];
break;
default:
cout << "ID number is invalid. please try again." << endl;
}
break;
} while (ID != 1111 || ID != 2222 || ID != 3333 || ID != 4444 || ID != 5555);
if (cash > 36.80)
{
cout << "You have $" << cash << " what stock would you like to purchase?" << endl;
listing();
cout << endl;
cout << "Type the stock symbol of the company that you would like to purchase." << endl;
cin >> sym;
double price;
int number_of_stock;
double total;
int i = 0;
while (i < 7)
{
Stock S_companies;
Companies >> S_companies.price[i];
i++;
}
//Stock S_companies;
if (sym == "AAPL" || sym== "aapl")
{
price = 450.00;
}
else if (sym == "BA" || sym == "ba")
{
price = 75.50;
}
else if (sym == "INTC" || sym == "intc")
{
price = 22.30;
}
else if (sym == "RMBS" || sym == "rmbs")
{
price = 5.55;
}
if (sym == "SIRI" || sym == "siri")
{
price = 3.15;
}
if (sym == "SWKS" || sym == "swks")
{
price = 25.35;
}
if (sym == "XLNX" || sym == "xlnx")
{
price = 36.80;
}
cout << "How many stock(s) would you like to buy?" << endl;
cin >> number_of_stock;
total = number_of_stock*price;
if (cash > total)
{
account S_account;
ofstream Oaccount;
Oaccount.open("Account.txt");
if (Oaccount.fail())
{
"Failed to open the file.";
}
I know this is where I need to edit but I am absolutely clueless on what to do so it only changes the account balance for the person that logged in using their ID.
if (ID == 1111)
{
Oaccount << S_accounts.id[0] << '\t' << '\t' << S_accounts.cash[0] - total;
}
Oaccount.close();
}
else
cout << "You do not have enough money.";
}
else
{
cout << "Sorry, you do not have enough money in your account.";
exit(1);
}
Account.close();
}
}
Im not debugging your code.But This is how you update/modify an entry...
let number be the value with which you want to find an account...lets say you want to change his name to newname...
while(!file.eof())
{
if(obj.number==given_value)
{
file.tellg(pos);
{
//modify values here like..
strcpy(obj.name,newname);
file.seekg(pos);
file.write((char*)&obj,sizeof(obj));
}
}
}