Simple program to calculate receipts

hi guyz, i'm new to this forum and new to c++, well programming in general, i've started to learn c++ nearly 2 mounths ago. So far i'm haveing so much fun and i haven't encounterd any problems yet.
However i would like to ask you guyz what you think about the code i wrote, my biggest concern is that i will pick up bad habbits in codeing style and would like to get guidlines along the learning path to be better in it.

I'm learning c++ as a hobbiest, i wan't to be able to write small GUI programs if i needed to insted expecting that someone else will do the work for me hehe.

I've made a simple receipt calculator that allows user to make/calculate as many receipts he wants and in the end print all receipts and their total and all receipts total on screen. I will soon make it have option to save all result into external txt file but there is no rush, this was just something to stop watching c++ video tutorials on youtube for a moment and start challangeing myself and testing what i've learn so far.

if you guyz have any suggestions, thoughts or critic about my codeing please feel free to tell me, i really appriciate it.

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
//============================================================================
// Name        : Receipts.cpp
// Author      : Ironman
// Version     : 0.3
// Copyright   : Your copyright notice
// Description : ReceiptsCalculator
//============================================================================

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

int main(){

	char choice; //used to store user action choice
	float userInputNumber; // used to store user price input
	float receiptTotal = 0; // used to temporally store receipt sum total before its final value is passed to vector element
	int receiptNum = 1; // used to store receipt number so it match's proper receipt enumeration before price input in each receipt
	vector<float> totalStorage;  //used to store receipts total as a vector element
	float totalStorageSum = 0; //used to store sum of all receipts total that are stored in vector

	//welcome message
	cout << "Receipt calculator by Ironman \n" << endl;

	//ask user which action he wants to perform
	cout << "Open new receipt? y/n ";
	cin >> choice;

	//as long user input is not n, run this loop
	while(choice != 'n'){

		//check if users input is valid
		while (choice !=  'y' && choice != 'n'){
			cout << "invalid input!! try again" << endl;
			cin >> choice;
		}

		// reset receipt total to 0, print receipt current number and ask for item price input
		receiptTotal = 0;
		cout << "\nReceipt " << receiptNum << "\n=====================" << "\n(-1) to close" << endl;
		cout << "Item: ";
		cin >> userInputNumber;

			//take user input, add it to receipt total and continue to do so until user enters -1
			while(userInputNumber != -1){
				receiptTotal += userInputNumber;
				cout << "Item: ";
				cin >> userInputNumber;
			}

		cout << "-------------------\n" << endl;

		//take receipt total and store it in a vector after it's last existing element and add 1 to receiptNumber.
		totalStorage.push_back(receiptTotal);
		receiptNum++;

		//ask user which action he wants to perform
		cout << "Open new receipt? y/n ";
		cin >> choice;
	}

	cout << endl;

	//print all receipts and their total in chronological order on screen
	for(int x=0; x<int(totalStorage.size()); x++){
		int z = (x+1);
		cout << "Receipt "<< z << ": " << totalStorage[x] << endl;
		totalStorageSum += totalStorage[x];
	}

	//print sum of all receipts total on screen
	cout << endl << "Total spent: " << totalStorageSum << "$";
}

Receipt calculator by Ironman 

Open new receipt? y/n y

Receipt 1
=====================
(-1) to close
Item: 12.25
Item: 21.54
Item: 10.02
Item: -5.25
Item: -1
-------------------

Open new receipt? y/n y

Receipt 2
=====================
(-1) to close
Item: 35.01
Item: 25.2
Item: 20
Item: -1
-------------------

Open new receipt? y/n n

Receipt 1: 38.56
Receipt 2: 80.21

Total spent: 118.77$


Last edited on
It's certainly not bad. I'd remove the unnecessary variable receiptNum and the code duplication as follows:
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
#include <iostream>
#include <vector>
using namespace std;

int main(){

	char choice = 'y'; //used to store user action choice
	float userInputNumber; // used to store user price input
	float receiptTotal = 0; // used to temporally store receipt sum total before its final value is passed to vector element
	int receiptNum = 1; // used to store receipt number so it match's proper receipt enumeration before price input in each receipt
	vector<float> totalStorage;  //used to store receipts total as a vector element
	float totalStorageSum = 0; //used to store sum of all receipts total that are stored in vector

	//welcome message
	cout << "Receipt calculator by Ironman \n" << endl;

	//ask user which action he wants to perform
	cout << "Open new receipt? y/n ";
	cin >> choice;

	//as long user input is not n, run this loop
	while(choice != 'n'){

		//check if users input is valid
		while (choice !=  'y' && choice != 'n'){
			cout << "invalid input!! try again" << endl;
			cin >> choice;
		}

		//ask user which action he wants to perform
		cout << "Open new receipt? y/n ";
		cin >> choice;
		if(choice == 'y'){

			// reset receipt total to 0, print receipt current number and ask for item price input
			receiptTotal = 0;
			cout << "\nReceipt " << totalStorage.size() + 1 receiptNum << "\n=====================" << "\n(-1) to close" << endl;
			cout << "Item: ";
			cin >> userInputNumber;

			//take user input, add it to receipt total and continue to do so until user enters -1
			do{
				receiptTotal += userInputNumber;
				cout << "Item: ";
				cin >> userInputNumber;
				if(userInputNumber >= 0)
					receiptTotal += userInputNumber;
			}
			while(userInputNumber != -1); // Note: direct comparison (==, !=) with float is dangerous (due to precision problems)

			cout << "-------------------\n" << endl;

			//take receipt total and store it in a vector after it's last existing element and add 1 to receiptNumber.
			totalStorage.push_back(receiptTotal);
			receiptNum++;
		}
		else if(choice != 'n')
			cout << "invalid input!! try again" << endl;
		//ask user which action he wants to perform
		cout << "Open new receipt? y/n ";
		cin >> choice;
	}

	cout << endl;

	//print all receipts and their total in chronological order on screen
	for(int x=0; x<int(totalStorage.size()); x++){
		int z = (x+1);
		cout << "Receipt "<< z << ": " << totalStorage[x] << endl;
		totalStorageSum += totalStorage[x];
	}

	//print sum of all receipts total on screen
	cout << endl << "Total spent: " << totalStorageSum << "$";
}
Last edited on
Wow, that is awesome man, so many good points there, you made it so much simpler in so many ways, plus you reused already existing vector for enumeration insted spending more memory on another variable. Also i will note that == != for floats thing.

I really appriciate your help, i learned a lot, simpler is always better :D
Welcome to the club! I started a bit before you but I"m still learning so take some of what I say as experience and some as wishful thinking :)

I put in your code and it complied no problems, that's step 1.

Good testing will prevent users and even yourself from doing something stupid in the future, I ran your code, put in the word test and it looped into never ever land. Also putting in a period causes the loop, but a .1 works ok.

So I recommend testing your code #2 and putting in some comments to the user so they know your program expects a number and not text. for Item:

I know this is personal taste, but I would change (-1) to close to (0) to close if that's not much trouble. again, personal taste, won't affect the program just the useability of it.

I would also change the loop method, someone ran the program, no reason to make them type Y to run it the first time. Put the Y/N after it's been ran one time. they can always type -1 to exit if they change their minds.

I also find this confusing, while perfectly legal.
cout << "-------------------\n" << endl;
If your goal is to make a blank line, I recommend
cout << "-------------------" << endl<<endl;

one last suggestion to make your program useful, after each Receipt, I would cout the total. So your new output would look something like :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Receipt calculator by Ironman

Open new receipt? y/n y

Receipt 1 - (0) to close
=====================
Item Amount: 1
Item Amount: 2
Item Amount: 3
Item Amount: 0
Total = 6

Open new receipt? y/n y

Receipt 2 - (0) to close
=====================
Item Amount: 2
Item Amount: 3
Item Amount: 4
Item Amount: 0
-------------------
Total = 9

Open new receipt? y/n n

Receipt 1: 6
Receipt 2: 9
=====================
Total spent: 15$


All in all, well written, and documented, so it's easy for others and yourself to understand it.

Below are my recommendations:
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
//============================================================================
// Name        : Receipts.cpp
// Author      : Ironman
// Version     : 0.3
// Copyright   : Your copyright notice
// Description : ReceiptsCalculator
//============================================================================

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

int main(){

	char choice; //used to store user action choice
	float userInputNumber; // used to store user price input
	float receiptTotal = 0; // used to temporally store receipt sum total before its final value is passed to vector element
	int receiptNum = 1; // used to store receipt number so it match's proper receipt enumeration before price input in each receipt
	vector<float> totalStorage;  //used to store receipts total as a vector element
	float totalStorageSum = 0; //used to store sum of all receipts total that are stored in vector

	//welcome message
	cout << "Receipt calculator by Ironman \n" << endl;

	//ask user which action he wants to perform
	cout << "Open new receipt? y/n ";
	cin >> choice;

	//as long user input is not n, run this loop
	while(choice != 'n'){

		//check if users input is valid
		while (choice !=  'y' && choice != 'n'){
			cout << "invalid input!! try again" << endl;
			cin >> choice;
		}

		// reset receipt total to 0, print receipt current number and ask for item price input
		receiptTotal = 0;
		cout << "\nReceipt " << receiptNum << " - (0) to close" << "\n====================="  << endl;
		cout << "Item Amount: ";
		cin >> userInputNumber;

			//take user input, add it to receipt total and continue to do so until user enters 0
			while(userInputNumber != 0){
				receiptTotal += userInputNumber;
				cout << "Item Amount: ";
				cin >> userInputNumber;
			}

		cout << "-------------------" << endl;
        cout << "Total = " << receiptTotal << endl<< endl;
		//take receipt total and store it in a vector after it's last existing element and add 1 to receiptNumber.
		totalStorage.push_back(receiptTotal);
		receiptNum++;

		//ask user which action he wants to perform
		cout << "Open new receipt? y/n ";
		cin >> choice;
	}

	cout << endl;

	//print all receipts and their total in chronological order on screen
	for(int x=0; x<int(totalStorage.size()); x++){
		int z = (x+1);
		cout << "Receipt "<< z << ": " << totalStorage[x] << endl;
		totalStorageSum += totalStorage[x];
	}

	//print sum of all receipts total on screen
    cout << "====================="<< endl;
	cout << "Total spent: " << totalStorageSum << "$";
}
Last edited on
Thank you for the warm welcome :)

So true, program indeed has flaws.

One of them is a char choice variable, while technicly check input loop will indeed do the job, if user enters more than 1 char it will make more Invalid Input couts. As many as there are chars entered.

i need to see how it could be done

Also, if user uses , insted . for decimals program will "crash"(never ending loop of item:)

i need to see how i could tell computer to treat , same as . char.(is it possible in c++)

and if user for instance enters just - insted -1 or char it will "crash" again, need to somehow specify not to accepts anything than what should be there.

No rush tho, little by little hehe

Again, thank you guyz so much for sharing your expiriance with me, i really do appriciate it. I'm really glad that i found this forum, you guyz are great!!

I only have youtube movies and c++ pdf tutorial from this site as learning material, non of my friends are programmers who could guide me.

Ofc, i'm not complaining just saying that your advices and guidlines guyz really helps me a lot ;)
Last edited on
I've took your advises and guidlines guyz and made new version of calculator, thx to you code is more readable, a lot less code lines and also more user friendly :)
I've added a new feature, it is possible now to save the calculation into txt file and choose save filename. For time being user will write a name for it, later ill make it automatic saving with name that contains date and time

I also wrote code to enable user to generate save list while saving a file, later there will be option to open a list of all saved files and then open the one user wants.
heres new code with save option and openFile(ofc you need to write at least one to have anything to open).
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
//============================================================================
// Name        : Receipts.cpp
// Author      : Ironman
// Version     : 0.4
// Copyright   : Your copyright notice
// Description : ReceiptsCalculator
//============================================================================

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;

string choice = "y"; //used to store user action choice
vector<float> totalStorage;  //used to store receipts total as a vector element
float totalStorageSum = 0; //used to store sum of all receipts total that are stored in vector

void newReceipt();
void saveReceipt();
void openReceipt();

int main()
{
	int menu;

	//welcome message
	cout << "Receipt calculator by Ironman" << endl << endl;

	cout << "What action you want to perform?\n1-New Receipt\n2-Open Receipt\n3-Exit\n\nchoice: ";
	cin >> menu;

	switch(menu)
	{
		case 1:
			newReceipt();
			saveReceipt();
				break;
		case 2:
			openReceipt();
				break;
		case 3:
			cout << endl << "Program ended!!" << endl;
				break;
	}

}

void newReceipt(){
	float userInputNumber; // used to store user price input
	float receiptTotal = 0; // used to temporally store receipt sum total before its final value is passed to vector element

	//as long user input is not n, run this loop
	while(choice != "n")
	{
		if(choice == "y")
		{
			// reset receipt total to 0, print receipt current number and ask for item price input
			receiptTotal = 0;
			cout << "\nReceipt " << (totalStorage.size())+1 << endl <<"====================\n(0)to close" << endl;

			//take user input, add it to receipt total and continue to do so until user enters 0
			do
			{
				cout << "ItemPrice: ";
				cin >> userInputNumber;
				receiptTotal += userInputNumber;
			}
			while(userInputNumber != 0);

			//print current receipt total
			cout << "--------------------" << endl;
			cout << "TotalCost: " << receiptTotal << endl << endl;

			//take receipt total and store it in a vector after it's last existing element
			totalStorage.push_back(receiptTotal);
			cout << "Open new receipt? y/n ";
			cin >> choice;


		}

		//if user choice wasn't neither y or n display invalid input message and tell user to repeat the input
		else if(choice != "n")
		{
			cout << "Invalid input, try again!" << endl;
			cout << "Open new receipt? y/n ";
			cin >> choice;
		}

	}
	cout << endl;

									                ///PRINT ON SCREEN///
	//////////////////////////////////////////////////////////////////////////////////////////////////////////

	//print all receipts and their totals in chronological order on screen
	for(int x=0; x<int(totalStorage.size()); x++)
	{
		cout << "Receipt "<< x+1 << ": " << totalStorage[x] << endl;
		totalStorageSum += totalStorage[x];
	}

	//print sum of all receipts total on screen
	cout << endl << "Total spent: " << totalStorageSum << "$\n" << endl;

	//////////////////////////////////////////////////////////////////////////////////////////////////////////
}



void saveReceipt(){
	//ask user for action
	cout << "Do you want to save? y/n ";
	cin >> choice;

	//check user input for validness
	while(choice != "n" && choice != "y")
	{
		//Invalid Input message
		cout << endl << "Invalid input, try again!" << endl;

		cout << "Do you want to save? y/n ";
		cin >> choice;
	}

	//if choice is equal to 'y' run this
	if(choice == "y")
	{
		cout << endl << "Name your file!" << endl;
		cout << "File name: ";
		cin >> choice;
		choice += ".txt"; //choice now becomes the holder of the filename with extension (.txt)

		//create/open file with name user has entered    NOTE: if file with that filename already exists it will be overwritten
		ofstream myFile(choice.c_str());

		//run a loop true out all vector elements and save them in chronological order to file
		for(int x = 0; x<int(totalStorage.size()); x++)
		{
			//write to file a receipt and its total in its own text row. Example:( Receipt 1 50)
			myFile << "Receipt" << ' ' << x+1 << ' ' << totalStorage[x] << endl;
		}

		//write sum of all receipts total and close the file
		myFile << endl << "Total:" << ' ' << totalStorageSum << endl;
		myFile.close();

		//clear the vector to free up memory
		totalStorage.resize(0);

		//save current file name in the fileList after last saved filename
		ofstream fileList("fileList.txt", ios::app);
		fileList << choice << endl;
		fileList.close();

		//tell user its saved
		cout << endl << "File Saved as " << choice << endl;
	}
}



void openReceipt()
{
	cout << endl << "Saved files\n=======================" << endl;

	//read the list
	ifstream myFile("fileList.txt");

    if(myFile.is_open())
    {
    	//prints all that it finds in the file
    	while(myFile >> choice)
    	{
    		cout << choice << endl;
    	}

    	myFile.close();
    	cout << "=======================" << endl << endl;

    	//ask which file you want to open
		cout << "Which file you want to open?" << endl;
		cin >> choice;


		cout << "file " << choice << " is opened!" << endl;
		cout << "=======================" << endl;

		//takes filename you wrote and opens it and prints everything that was in it
		ifstream openFile(choice.c_str());

		while(!openFile.eof())
		{
			getline(openFile, choice);
			cout << choice << endl;
		}
		openFile.close();

    }
    else
    {
    	cout << "Empty!!";
    }



}




make a receit
Receipt calculator by Ironman

What action you want to perform?
1-New Receipt
2-Open Receipt
3-Exit

choice: 1

Receipt 1
====================
(0)to close
ItemPrice: 500
ItemPrice: 0
--------------------
TotalCost: 500

Open new receipt? y/n n

Receipt 1: 500

Total spent: 500$

Do you want to save? y/n y

Name your file!
File name: fileeeee

File Saved as fileeeee.txt


file opend
Receipt calculator by Ironman

What action you want to perform?
1-New Receipt
2-Open Receipt
3-Exit

choice: 2

Saved files
=======================
hello.txt
novi.txt
HelloKitty.txt
fifi.txt
fileeeee.txt
=======================

Which file you want to open?
fileeeee.txt
file fileeeee.txt is opened!
=======================
Receipt 1 500

Total: 500



text file
Receipt 1 500

Total: 500

Last edited on
Topic archived. No new replies allowed.