Value keeps resetting once I go back to the menu

I'm having a hard time thinking how can I change my variable after it executes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include "Register.h"
#include <iostream>
#include <fstream>
#include <string>

Register::Register()
{
    //ctor
}

Register::~Register()
{
    //dtor
}
void Register::logMenu()
{
    int pick = -1;
    Register login;

    while(pick != 0)
    {
        cout << "\n Login Menu" << endl;
        cout << "================================" << endl;
        cout << "[1] - Reserve Tickets" << endl;
        cout << "[2] - Edit Ticket's Information" << endl;
        cout << "[3] - Cancel a Ticket" << endl;
        cout << "[0] - Exit" << endl;

        cout << "\nEnter a Menu Number to proceed: ";
        cin >> pick;

        cin.clear();
        fflush(stdin);

        switch(pick)
        {
            case 1:
                login.table();
                break;
            case 2:
                login.modify();
                break;
            case 3:
                login.cancel();
                break;
            case 0:
                cout << "Thank you, Please come again!" << endl;
                break;
            default:
                pick = 0;
                break;
        }
    }
}
void Register::table()
{
    cout << "\n";
    cout << "--------------------------------------------------------------------------------------------------------------------------" << endl;
	cout << " Train Name"<<"               "<<"Departure Time"<<"     "<<"Arrival Time"<<"     "<<"Boarding Point"<<"         "<<"Destination"<<"             "<<"Price"<< endl;
	cout << "--------------------------------------------------------------------------------------------------------------------------" << endl;
	cout << " Manila Express"<<"              "<<"6:00 AM"<<"           "<<"6:30 AM"<<"        "<<"Baclaran"<<"               "<<"Roosevelt"<<"                "<<" 50"<< endl;
	cout << "--------------------------------------------------------------------------------------------------------------------------" << endl;
	cout << " Luzon Express Line"<<"          "<<"6:00 AM"<<"           "<<"7:00 AM"<<"        "<<"Santolan"<<"               "<<"Recto"<<"                    "<<" 75"<< endl;
	cout << "--------------------------------------------------------------------------------------------------------------------------" << endl;
	cout << " Dakila Train"<<"                "<<"7:00 AM"<<"           "<<"7:20 AM"<<"        "<<"North Avenue"<<"           "<<"Taft Avenue"<<"              "<<" 40"<< endl;
	cout << "--------------------------------------------------------------------------------------------------------------------------" << endl;
	cout << " Golden Train"<<"                "<<"6:30 AM"<<"           "<<"7:00 AM"<<"        "<<"Taytay"<<"                 "<<"Magsaysay Boulevard"<<"      "<<"250"<< endl;
	cout << "--------------------------------------------------------------------------------------------------------------------------" << endl;
	cout << " Puting Rosas"<<"                "<<"6:00 AM"<<"           "<<"6:20 AM"<<"        "<<"Ayala Avenue"<<"           "<<"Cembo"<<"                    "<<" 65"<< endl;
	cout << "--------------------------------------------------------------------------------------------------------------------------" << endl;
	cout << " Cavite Express"<<"              "<<"6:15 AM"<<"           "<<"6:45 AM"<<"        "<<"Paco"<<"                   "<<"Naic"<<"                     "<<" 90"<< endl;
	cout << "--------------------------------------------------------------------------------------------------------------------------" << endl;
	cout << " Modern Express Train"<<"        "<<"8:00 AM"<<"           "<<"8:15 AM"<<"        "<<"San Jose del Monte"<<"     "<<"North Avenue"<<"             "<<"120"<< endl;
	cout << "--------------------------------------------------------------------------------------------------------------------------" << endl;
	cout << " Quezon Express"<<"              "<<"6:45 AM"<<"           "<<"7:15 AM"<<"        "<<"University Avenue"<<"      "<<"Lerma"<<"                    "<<" 35"<< endl;
	cout << "--------------------------------------------------------------------------------------------------------------------------" << endl;
	cout << " Pulang Kabayo"<<"               "<<"7:00 AM"<<"           "<<"7:30 AM"<<"        "<<"Quirino Highway"<<"        "<<"NAIA Terminal 3"<<"          "<<" 60"<< endl;
	cout << "--------------------------------------------------------------------------------------------------------------------------" << endl;
	cout << " PNR Metropolitan Train"<<"      "<<"6:00 AM"<<"           "<<"6:45 AM"<<"        "<<"Tutuban"<<"                "<<"IRRI (MSC)"<<"               "<<" 30"<< endl;
	cout << "--------------------------------------------------------------------------------------------------------------------------" << endl;

	reserve();
}
void Register::results(int &x, int &y, int &z)
    {
        x = y - z;
    }
void Register::reserve()
{
    string trainName;
    int seats;

    cout << "\tWhat train would you like to board passenger?" << endl;
    cout << "\tPlease input the name of the train below." << endl;
    cout << "\tNote: All trains have a maximum boarding capacity of 50." << endl;

    cout << "\nTrain Name: ";
    getline(cin,trainName);

    cout << "Number of Seats: ";
    cin >> seats;

    int mc[10]= {50, 50, 50, 50, 50 ,50, 50, 50, 50, 50};  // maximum capacity
    int ctr[10]= {50, 50, 50, 50, 50 ,50, 50, 50, 50, 50};
    int price;

    if ((trainName == "Manila Express")||("manila express"))
    {
        price = 50 * seats;
        ctr[0] = mc[0] - seats;
        if (mc[0]==0)
        {
            cout << "\nSorry there are no more seats available on the Manila Express." << endl;
            cout << ctr[0];
        }
        else
        {
            cout << "\nYou have successfully purchased " << seats << " tickets for the Manila express! See you on board!" << endl;
            cout << ctr[0];
        }
    }
    else
    {
        cout << "Wrong Input!" << endl;
    }



}


In void Register::reserve(), if I buy 50 tickets in a train, it's supposed to subtract and update its value but that isn't the case. Can someone please help me? I've been trying to figure out this problem for so long.
Last edited on
What variable are you specifically referring to?

Some issues I see:

(1) You initially set mc[0] to be 50, but you never change this value, so your if statement on line 111 will always be false. Is that intentional? It looks like you should be comparing against cr[0] and not mc[0]. Also, your mc and ctr arrays are of length 10, but you only ever use the first value (index 0).

(2) Your if statement on line 107 will always be true, because string literals like "hello" will always be evaluated to a non-zero value.
You meant: if (trainName == "Manila Express" || trainName == "manila express")
Last edited on
YES! Thank you for responding Ganado!!

My main issue is exactly your first point. I didn't notice that, but anyways I changed the value to
mc[0]= ctr[0] - seats;
And it still resets my value to 50. Like when I buy 28 tickets, it says that there are only 22 tickets left, but when I go back to the switch(pick) and go through void Register::reserve() again, and I buy like 50 tickets, it still allows me to go through. I'm stuck.


"Also, your mc and ctr arrays are of length 10, but you only ever use the first value (index 0)."
I didn't post my whole code here since it didn't fit, but it was basically a repeated if and else of line 107 to 121. They all reset to the value 50.

"(2) Your if statement on line 107 will always be true, because string literals like "hello" will always be evaluated to a non-zero value."
I didn't even notice that that was a problem, but thank you! I'll try to fix it.
Last edited on
The mc and ctr arrays are local the reserve function, and are re-created every time reserve is called. If you want the changes in values to persist over multiple calls to reserve, you need to put the array you want to change in a larger scope, for example the class scope.

So in your class you might have something like:

1
2
3
4
5
6
7
class Register {
    public:
        // ...

   private:
    int available_seats[10] { 50, 50, 50, 50, 50,   50, 50, 50, 50, 50 };
};


Then, in your register function, you can write something like:
available_seats[0] -= seats_purchased;
So I just did that here in Register.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#ifndef REGISTER_H
#define REGISTER_H
#include <string>

using namespace std;

class Register
{
    public:
        Register();
        virtual ~Register();

        int age,phone;
        string gender,name,username,password;


        void logMenu();
        void table();
        void reserve();
        void modify();
        void cancel();
        void exit();


    protected:

    private:
        int mc[10]= {50, 50, 50, 50, 50 ,50, 50, 50, 50, 50};  // maximum capacity
        int ctr[10]= {50, 50, 50, 50, 50 ,50, 50, 50, 50, 50};
        int price;
};

#endif // REGISTER_H 

And I am pissed that it still doesn't persist throughout, like I'm still able to buy 30 tickets, go back, and buy another 40 tickets. I don't know what to do. I'm sorry for taking your time on me.
No worries, show what your reserve function looks like now.
Last edited on
Sorry for the late reply! So here's where's it at right now:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
void Register::reserve()
{
    string trainName;
    int seats;

    cout << "\tWhat train would you like to board passenger?" << endl;
    cout << "\tPlease input the name of the train below." << endl;
    cout << "\tNote: All trains have a maximum boarding capacity of 50." << endl;

    cout << "\nTrain Name: ";
    getline(cin,trainName);

    cout << "Number of Seats: ";
    cin >> seats;

    int mc[10]= {50, 50, 50, 50, 50 ,50, 50, 50, 50, 50};  // maximum capacity
    int ctr[10]= {50, 50, 50, 50, 50 ,50, 50, 50, 50, 50};
    int price;

    if (trainName == "Manila Express" || trainName == "manila express")
    {
        price = 50 * seats;
        ctr[0] = mc[0] - seats;
        if (ctr[0]==0)
        {
            cout << "\nSorry there are no more seats available on the Manila Express." << endl;
            cout << ctr[0];
        }
        else
        {
            cout << "\nYou have successfully purchased " << seats << " tickets for the Manila express! See you on board!" << endl;
            cout << ctr[0];
        }
    }
    else
    {
        cout << "Wrong Input!" << endl;
    }
}

So I changed mc[0] to ctr[0] as you said but it's still giving me the same results.
Now that you've defined mc/ctr in your class definition, don't redefine them as local variables on lines 16/17. Remove those lines.
Why do you create local variables on line 16-18 instead of using the class variables?
BTW. Your code would be much easier if you had a struct Train like this.
1
2
3
4
5
6
struct Train
{
  string name;
  int avail_seats;
  int ticket_price;
};

Then you need only one array for all trains.
To Ganado: Yes, thank you I just removed them. What should I do after?
To thmm: I'm sorry. Structs were just now taught to us this past week by our professor. We weren't able to apply it to our project since we had already started on it.
What should I do after?
Run your program, note its behavior, explain how its behavior differs from the expected/desired behavior. If you were expecting a particular value to be different than what it actually is, run through your code with a debugger so you can see what the values of the variables are while the program is running (or, use print statements to print out the values of variables in question).

From your latest post, two things I see are questionable:
(1) You should probably be checking if there are [seats] available seats in your array before subtracting the seats and going through with the purchase.
(2) Explain the purpose/difference between your two different arrays, mc and ctr. Perhaps give them better names.

Your logic here:
ctr[0] = mc[0] - seats; will still always be doing ctr[0] = 50 - seats, because mc[0] is never updated.

I would just have one array, for example,
int available_seats[10] = {50, 50, 50, 50, 50, 50, 50, 50, 50, 50};

Then, when the user attempts to purchase a seat:

1
2
3
4
5
6
7
8
9
10
11
12
13
if (available_seats[0] == 0)
{
    // No more seats available
}
else if (seats > available_seats[0])
{
    // Not enough seats!
}
else
{
    // Purchase the seats, subtract the bought seats from the available seats
    available_seats[0] -= seats;
}
Last edited on
1
2
3
4
if (trainName == "Manila Express" || trainName == "manila express")
    {
        price = 50 * seats;
        ctr[0] = mc[0] - seats;


Based upon this code, are you planning to have similar statements to check for each train name and alter ctr[1], mc[1] if the train name is Luzon Express Line and then test for train Dakila Train etc etc etc?? If yes, then this is not how you code it. You'll have effectively 10 sets of code that essentially does the same. As you're doing classes, you know about functions etc. You should also know about structs as mentioned above. Usually the info displayed in the table() member function would be stored in a file and read in. Your program should know nothing about any specific data values - just the structure and type of data. The program then operates on this structure/data.

Before you go any further, I'd suggest you take a step backward, produce a proper program/class design and then code from the design. Normally, for example, logmenu member function wouldn't be part of the class and wouldn't have a variable of the type class that's being defined!
Based upon file data, consider as a start:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <iostream>
#include <vector>
#include <string>
#include <fstream>

struct Trains {
	std::string name;
	std::string dep;
	std::string arriv;
	std::string board;
	std::string dest;
	int seats {50};
};

int getInt(const std::string& prm)
{
	int i {};

	while ((std::cout << prm) && (!(std::cin >> i) || !std::isspace(std::cin.peek()))) {
		std::cout << "Not an integer\n";
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}

	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	return i;
}

std::istream& operator>>(std::istream& is, Trains& train)
{
	std::getline(is, train.name, ',');
	std::getline(is, train.dep, ',');
	std::getline(is, train.arriv, ',');
	std::getline(is, train.board, ',');
	std::getline(is, train.dest);

	return is;
}

std::ostream& operator<<(std::ostream& os, const Trains& train)
{
	return os << train.name << "  " << train.dep << "  " << train.arriv << "  " << train.board << "  " << train.dest << "  " << train.seats;
}

class Register {
public:
	Register(const std::string& fn) {
		std::ifstream iftrains("trains.txt");

		for (Trains t; iftrains >> t; trains.push_back(t));
	}

	void reserve() {

		int trainno {}, num {};

		do {
			trainno = getInt("What train would you like to board passenger (enter train number) : ");
		} while ((trainno < 1 || trainno > trains.size()) && (std::cout << "Invalid train number\n"));

		--trainno;

		auto& seats {trains[trainno].seats};

		if (seats == 0) {
			std::cout << "There are no seats available\n";
			return;
		}

		do {
			std::cout << "There are " << seats << " available\n";
			num = getInt("Number of Seats: ");
		} while ((num < 1 || num > seats) && (std::cout << "Invalid number of seats\n"));

		seats -= num;

		std::cout << "\nYou have successfully purchased " << num << " tickets for the " << trains[trainno].name << "! See you on board!\n";
	};

	void edit() {};
	void cancel() {};
	size_t notrains() const { return trains.size(); }

	void display() const {
		for (size_t tno = 0; const auto& t : trains)
			std::cout << ++tno << "  " << t << '\n';
	}

private:
	std::vector<Trains> trains;
};

int main()
{
	Register reg("trains.txt");

	if (reg.notrains() == 0)
		return (std::cout << "Cannot read input file\n"), 1;

	for (int pick = 99; pick != 0; ) {
		std::cout << "\nLogin Menu\n";
		std::cout << "================================\n";
		std::cout << "[1] - Reserve Tickets\n";
		std::cout << "[2] - Edit Ticket's Information\n";
		std::cout << "[3] - Cancel a Ticket\n";
		std::cout << "[4] - Display\n";
		std::cout << "[0] - Exit\n";

		switch (pick = getInt("\nEnter a Menu Number to proceed: ")) {
			case 1: reg.reserve(); break;
			case 2: reg.edit(); break;
			case 3: reg.cancel(); break;
			case 4: reg.display(); break;

			case 0:
				std::cout << "Thank you, Please come again!\n";
				break;

			default:
				std::cout << "Invalid menu number\n";
				break;
		}
	}
}


With the input file as:


Manila Express,6:00 AM,6:30 AM,Baclaran,Roosevelt
Luzon Express Line,6:00 AM,7:00 AM,Santolan,Recto
Dakila Train,7:00 AM,7:20 AM,North Avenue,Taft Avenue

Topic archived. No new replies allowed.