(C++) Code seems to be operating off the wrong loop...? - c++

I've been playing around with some code in my down-time from my degree and I've nested a do{}while() loop inside another one but the problem I'm having is that the code keeps going until the last van is full, even after the number of parcels has been fulfilled...
The code's below. If someone could take a look at it and tell me what I've done wrong that'd be awesome. Bare in mind I've only really been coding in C++ for about a month so I've still got hella lot to learn..
#include <iostream>
using namespace std;
char cBeltFull;
int iVanCount, iParcelCount, iParcelLoaded;
float fHeaviestVanWeight, fParcelWeight, fCurrentPayload, fVanCapacity;
char cExit = 'N';
int main() {
iVanCount = 1;
iParcelLoaded = 1;
fHeaviestWeight = 0;
fVanCapacity = 410;
do {
//Get the number of parcels to dispatch
cout << "How many parcels need sending?" << endl;
cin >> iParcelCount;
do {
fCurrentPayload = 0;
do {
//Get parcel weight
cout << endl << endl << endl << "What is the weight the parcel " << iParcelLoaded << "?";
cin >> fParcelWeight;
//'Load' the parcel
cout << endl << endl << "Parcel loaded";
iParcelLoaded ++;
//Update the payload
fCurrentPayload = fCurrentPayload + fParcelWeight;
} while ((fCurrentPayload + fParcelWeight)) < fVanCapacity)
//Dispatch the van
cout << endl << endl << "Van dispatched.";
//Update the van count
iVanCount ++;
if (fCurrentPayload > fHeaviestVanWeight) {
//Update the heaviest weight
fHeaviestVanWeight = fCurrentPayload;
}
} while (iParcelLoaded <= iParcelCount);
cout << endl << endl << endl << "Vans dispatched: " << iVanCout;
cout << endl << endl << "Weight of heaviest van: " << fHeaviestWeight;
cout << endl << endl << endl << "Exit? Y for YES or N for NO." << endl;
cin >> cExit;
} while (cExit == 'N');
}

Change this
} while (((fCurrentPayload + fParcelWeight)) < fVanCapacity);
to this
} while (((fCurrentPayload + fParcelWeight)) < fVanCapacity
&& iParcelLoaded < iParcelCount);
That way you will load as many items the user inputs. You code contains many syntax errors.
I corrected them for you, but please be more careful next time you post.
#include <iostream>
using namespace std;
char cBeltFull;
int iVanCount, iParcelCount, iParcelLoaded;
float fHeaviestVanWeight, fParcelWeight, fCurrentPayload, fVanCapacity;
char cExit = 'N';
int main() {
iVanCount = 1;
iParcelLoaded = 1;
fHeaviestVanWeight = 0;
fVanCapacity = 410;
do {
//Get the number of parcels to dispatch
cout << "How many parcels need sending?" << endl;
cin >> iParcelCount;
do {
fCurrentPayload = 0;
do {
//Get parcel weight
cout << endl << endl << endl << "What is the weight the parcel " << iParcelLoaded << "?";
cin >> fParcelWeight;
//'Load' the parcel
cout << endl << endl << "Parcel loaded";
iParcelLoaded ++;
//Update the payload
fCurrentPayload = fCurrentPayload + fParcelWeight;
} while (((fCurrentPayload + fParcelWeight)) < fVanCapacity && iParcelLoaded < iParcelCount);
//Dispatch the van
cout << endl << endl << "Van dispatched.";
//Update the van count
iVanCount ++;
if (fCurrentPayload > fHeaviestVanWeight) {
//Update the heaviest weight
fHeaviestVanWeight = fCurrentPayload;
}
} while (iParcelLoaded <= iParcelCount);
cout << endl << endl << endl << "Vans dispatched: " << iVanCount;
cout << endl << endl << "Weight of heaviest van: " << fHeaviestVanWeight;
cout << endl << endl << endl << "Exit? Y for YES or N for NO." << endl;
cin >> cExit;
} while (cExit == 'N');
}

Related

How to store multiple string inputs and displaying it after

I'm just starting in studying C++, and I am doing a simple challenge which is GWA Calculator, but I am having a problem finding out how to store the multiple strings input (which is the Subjects/Course) and displaying it after together with the Units and Grades. I am really sorry, but I tried finding out how and I couldn't find an answer. Hope you can help me out.
#include <stdlib.h>
using namespace std;
void calculateGWA();
int main()
{
system("cls");
int input;
cout << "\t\t -------------------------------------------------------------------------- " << endl;
cout << "\t\t| GWA Calculator |" << endl;
cout << "\t\t -------------------------------------------------------------------------- " << endl;
cout << "\t\t| MENU:\t\t\t\t\t\t\t " << "|" << endl;
cout << "\t\t| 1. Calculate GWA (General Weighted Average)\t\t " << "|" << endl;
cout << "\t\t| 2. Calculate CGWA (Cummulative Weighted Average) " << "|" << endl;
cout << "\t\t| 4. Exit Application\t\t\t\t\t " << "|" << endl;
cout << "\t\t| |" << endl;
cout << "\t\t -------------------------------------------------------------------------- " << endl;
sub:
cout << "\t\tEnter your choice: ";
cin >> input;
switch(input)
{
case 1:
calculateGWA();
break;
case 2:
//calculateCGPA();
break;
case 3:
main();
break;
case 4:
exit(EXIT_SUCCESS);
break;
default:
cout << "You have entered wrong input.Try again!\n" << endl;
goto sub;
break;
}
}
void calculateGWA()
{
int q;
system("cls");
cout << "-------------- GWA Calculator -----------------"<<endl;
cout << " How many course(s)?: ";
cin >> q;
char c_name[50];
float unit [q];
float grade [q];
cout << endl;
for(int i = 0; i < q; i++)
{
cout << "Enter the Course Name " << i+1 << ": ";
cin >> c_name;
cout << "Enter the Unit " << c_name << ": ";
cin >> unit[i];
cout << "Enter the Grade " << c_name << ": ";
cin >> grade[i];
cout << "-----------------------------------\n\n" << endl;
}
float sum = 0;
float tot;
for(int j = 0; j < q; j++)
{
tot = unit[j] * grade[j];
sum = sum + tot;
}
float totCr = 0;
for(int k = 0; k < q; k++)
{
totCr = totCr + unit[k];
}
system("cls");
// PRINTS OUT THE COURSES - UNITS - GRADES AND GWA //
cout << "\t\t =============================================================== " << endl;
cout << "\t\t| COURSE | UNIT | GRADE |" << endl;
cout << "\t\t =============================================================== " << endl;
cout << "Total Points: " << sum << " \n Total Credits: " << totCr << " \nTotal GPA: " << sum/totCr << " ." << endl;
cout << c_name << "\n" << endl;
cout << "===================================" << endl;
sub:
int inmenu;
cout << "\n\n\n1. Calculate Again" << endl;
cout << "2. Go Back to Main Menu" << endl;
cout << "3. Exit This App \n\n" << endl;
cout << "Your Input: " << endl;
cin >> inmenu;
switch(inmenu)
{
case 1:
calculateGPA();
break;
case 2:
main();
break;
case 3:
exit(EXIT_SUCCESS);
default:
cout << "\n\nYou have Entered Wrong Input!Please Choose Again!" << endl;
goto sub;
}
}

gotoxy prints wrong in c++

I am making a menu for a store with 4 options; add product, delete product, see table of created products and exit the program.
I finished the option to add products and exit, they both work fine.
Now I have to make the option to see the product table, supposedly I had already finished it but I noticed a problem ...
The first time I go in to see the product table, it prints it to me normally, like this.
enter image description here
But when I go to the menu and go back to the product table, it prints it like this.
enter image description here
Like I said, it only prints it right the first time I see it, then it prints it wrong.
Do you know how I can solve it?
This is the part of the code where I print the product table.
void table()
{
int c = k, m = 7;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 4;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
This is my complete code (maybe I have one or another library too many because I have been experimenting).
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
#include<ctype.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
struct products
{
int numor{},
cant{};
float preuni{},
subt{},
IVA{},
total{};
string cod{};
string descr{};
}product[51];
void add();
void intro_code();
int val_code(char codigo[]);
void table();
void gotoxy(int x, int y);
int i = 1; //Product No. (counter)
int k = 1; //Consecutive number (counter)
int main()
{
char opc;
cout << " Welcome ";
cout << endl;
cout << "\n1.- Add product.";
cout << "\n2.- Delete product.";
cout << "\n3.- Table of created products.";
cout << "\n4.- Exit";
cout << endl;
cout << "\nWhat do you want to do today?: "; cin >> opc;
switch (opc)
{
case '1':
system("cls");
cout << "\nAdd product";
add();
system("pause");
system("cls");
return main();
case '2':
cout << "\nDelete product";
system("cls");
return main();
case '3':
table();
return main();
case '4':
exit(EXIT_SUCCESS);
default:
system("cls");
cout << "Warning: the data entered is not correct, try again.\n\n";
return main();
}
return 0;
}
void add()
{
int can;
cout << "\nHow many products do you want to register?: "; cin >> can;
if (can <= 0 || can > 51)
{
system("cls");
cout << "Warning: The amount of products entered is not valid, try again";
return add();
}
for (int p = 1; p <= can;)
{
if (i < 51)
{
if (k <= 51) // In this part, consecutive numbers are generated automatically
{
cout << "\nNumber of order: ";
cout << k;
cout << endl;
product[i].numor = k;
k++;
}
cin.ignore();
cout << "Name of product: ";
getline(cin, product[i].descr);
intro_code();
cout << "Quantity to sell: "; cin >> product[i].cant;
cout << "unit price: $"; cin >> product[i].preuni;
product[i].subt = product[i].preuni * product[i].cant;
cout << "Subtotal: $" << product[i].subt;
product[i].IVA = product[i].subt * 0.16;
cout << "\nIVA: $" << product[i].IVA;
product[i].total = product[i].subt + product[i].IVA;
cout << "\nTotal price: $" << product[i].total;
cout << "\n-------------------------------------------------------------------------------";
cout << endl;
i++;
}
p++;
}
}
/*In this function the product code is entered, if the user enters a code
less than or greater than 5 characters the program displays an error message and allows the
user try again.*/
void intro_code()
{
char hello[10];
int xyz;
do {
cout << "Code of product (5 digits): ";
cin.getline(hello, 10, '\n');
if (strlen(hello) != 5)
{
cout << "The data entered is incorrect, try again ...";
cout << endl;
return intro_code();
}
else
{
xyz = val_code(hello);
}
} while (xyz == 0);
product[i].cod = hello;
}
/*As the requirement for "product code" is that it does not contain letters, special characters or blank spaces
create the function val_code to go through each character entered in the code, check character by character with the isdigit function
to see if the character is numeric or not, if it is not numeric it prints a warning message and allows the user to try again
without leaving the console.*/
int val_code(char hello[]) {
int abc;
for (abc = 0; abc < strlen(hello); abc++) {
if (!(isdigit(hello[abc]))) {
cout << "The data entered is incorrect, try again ...";
cout << endl;
return 0;
}
}
return 1;
}
void table()
{
int c = k, m = 7;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 4;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
void gotoxy(int x, int y)
{
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
Thank you very much in advance :)
The main reason for this problem is that after the size of the console changes, the position of the symbols you draw has also changed. At the same time, the line break determined by cout<<endl; also has a problem. For example, after the window becomes larger, the line length of the console becomes larger, but cout<<endl; is still the original line length.
However, there is no good solution. I suggest you directly set the console size and m=5, m=m+2.
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
#include<ctype.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
struct products
{
int numor{},
cant{};
float preuni{},
subt{},
IVA{},
total{};
string cod{};
string descr{};
}product[51];
void add();
void intro_code();
int val_code(char codigo[]);
void table();
void gotoxy(int x, int y);
int i = 1; //Product No. (counter)
int k = 1; //Consecutive number (counter)
int main()
{
HWND console = GetConsoleWindow();
RECT r;
GetWindowRect(console, &r);
MoveWindow(console, r.left, r.top, 1400, 400, TRUE);
char opc;
cout << " Welcome ";
cout << endl;
cout << "\n1.- Add product.";
cout << "\n2.- Delete product.";
cout << "\n3.- Table of created products.";
cout << "\n4.- Exit";
cout << endl;
cout << "\nWhat do you want to do today?: "; cin >> opc;
switch (opc)
{
case '1':
system("cls");
cout << "\nAdd product";
add();
system("pause");
system("cls");
return main();
case '2':
cout << "\nDelete product";
system("cls");
return main();
case '3':
table();
return main();
case '4':
exit(EXIT_SUCCESS);
default:
system("cls");
cout << "Warning: the data entered is not correct, try again.\n\n";
return main();
}
return 0;
}
void add()
{
int can;
cout << "\nHow many products do you want to register?: "; cin >> can;
if (can <= 0 || can > 51)
{
system("cls");
cout << "Warning: The amount of products entered is not valid, try again";
return add();
}
for (int p = 1; p <= can;)
{
if (i < 51)
{
if (k <= 51) // In this part, consecutive numbers are generated automatically
{
cout << "\nNumber of order: ";
cout << k;
cout << endl;
product[i].numor = k;
k++;
}
cin.ignore();
cout << "Name of product: ";
getline(cin, product[i].descr);
intro_code();
cout << "Quantity to sell: "; cin >> product[i].cant;
cout << "unit price: $"; cin >> product[i].preuni;
product[i].subt = product[i].preuni * product[i].cant;
cout << "Subtotal: $" << product[i].subt;
product[i].IVA = product[i].subt * 0.16;
cout << "\nIVA: $" << product[i].IVA;
product[i].total = product[i].subt + product[i].IVA;
cout << "\nTotal price: $" << product[i].total;
cout << "\n-------------------------------------------------------------------------------";
cout << endl;
i++;
}
p++;
}
}
/*In this function the product code is entered, if the user enters a code
less than or greater than 5 characters the program displays an error message and allows the
user try again.*/
void intro_code()
{
char hello[10];
int xyz;
do {
cout << "Code of product (5 digits): ";
cin.getline(hello, 10, '\n');
if (strlen(hello) != 5)
{
cout << "The data entered is incorrect, try again ...";
cout << endl;
return intro_code();
}
else
{
xyz = val_code(hello);
}
} while (xyz == 0);
product[i].cod = hello;
}
/*As the requirement for "product code" is that it does not contain letters, special characters or blank spaces
create the function val_code to go through each character entered in the code, check character by character with the isdigit function
to see if the character is numeric or not, if it is not numeric it prints a warning message and allows the user to try again
without leaving the console.*/
int val_code(char hello[]) {
int abc;
for (abc = 0; abc < strlen(hello); abc++) {
if (!(isdigit(hello[abc]))) {
cout << "The data entered is incorrect, try again ...";
cout << endl;
return 0;
}
}
return 1;
}
void table()
{
int c = k, m = 5;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 2;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
void gotoxy(int x, int y)
{
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
In addition, it is not recommended that you use cmd to make gui.

C++ Program need help to debug

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct football_game
{
string visit_team;
int home_score;
int visit_score;
};
void printMenu();
int main()
{
int i, totalValues = 0;
ifstream inputFile;
string temp = "";
inputFile.open("games.txt");
if (!inputFile)
{
cout << "Error opening Input file!" << endl;
exit(101);
}
inputFile >> totalValues;
getline(inputFile, temp);
cout << " *** Football Game Scores *** " << endl << endl;
cout << " * Total Number of teams : " << totalValues << endl << endl;
football_game* records = new football_game[totalValues];
// while (!inputFile.eof())
// {// == NULL) {
for (i = 0; i < totalValues; i++)
{
getline(inputFile, records[i].visit_team);
cout << records[i].visit_team << endl;
inputFile >> records[i].home_score >> records[i].visit_score;
cout << records[i].home_score << " " << records[i].visit_score << endl;
getline(inputFile, temp);
}
//}
cout << endl;
int choice = 0;
int avg_home_Score = 0;
int avg_visit_Score = 0;
printMenu(); // prints menu
cout << "Please Enter a choice from the Menu : ";
cin >> choice;
cout << endl << endl;
while (true)
{
switch (choice)
{
case 1:
cout << " Score Table " << endl;
cout << " ***********************" << endl << endl;
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
for (int i = 0; i < totalValues; i++)
{
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|' << setw(7)
<< right << records[i].visit_score << " " << '|' << endl;
}
cout << endl << endl << endl;
break;
case 2:
{
string team_name;
cout << "Enter the Team Name : ";
cin >> team_name;
for (int i = 0; i < totalValues; i++)
{
if (records[i].visit_team == team_name)
{
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|'
<< setw(7) << right << records[i].visit_score << " " << '|'
<< endl;
}
}
cout << endl;
break;
}
case 3:
{
for (int i = 0; i < totalValues; i++)
avg_home_Score += records[i].home_score;
cout << "Average home_score: " << (avg_home_Score / totalValues) << endl << endl;
break;
}
case 4:
{
for (int i = 0; i < totalValues; i++)
avg_visit_Score += records[i].visit_score;
cout << "Average visit_score: " << (avg_visit_Score / totalValues) << endl << endl;
break;
}
default:
{
cout << "Please enter valid input !!" << endl;
break;
}
}
printMenu();
cin >> choice;
}
return 0;
}
void printMenu()
{
cout << " Menu Options " << endl;
cout << " ================ " << endl;
cout << " 1. Print Information of all Games[Table Form] " << endl;
cout << " 2. Print Information of a Specific Game " << endl;
cout << " 3. Print Average points scored by the Home Team during season" << endl;
cout << " 4. Print Average points scored against the Home Team" << endl << endl << endl;
}
Here is the input file i am using
games.txt
5
SD Mines
21 17
Northern State
10 3
BYU
10 21
Creighton
14 7
Sam Houston State
14 24
When i am using the 2nd option (Print Information of a Specific Game) from the output screen,
it ask me to enter the team name and when i enter the team-name.
For example: SD Mines it gives me an error, but when I enter the team-name with no space like: BYU it works fine for me.
cin >> team_name;
Takes the input only upto space.
You might want to use cin.getline() for taking space separated strings as input.
A small program demonstrating the same :
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Name is : , " << name << "!\n";
return 0;
}
std::cin ignores whitespaces by default.
To include spaces in your input try :
getline(cin, team_name);
This would pick up all the characters in a line until you press enter. This is available in
#include<string>
You need to flush the std::cin buffer after reading the choice:
#include <limits>
//...
cin >> choice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Refer to this question for detailed explanation.
Also, if you want to read strings with spaces from the standard input, replace this:
cin >> team_name;
with this:
getline(cin, team_name);
as already mentioned in other answers. No need to flush std::cin this time, since you have already read the full line.
Finally, remove extra newlines from your games.txt:
5
SD Mines
21 17
Northern State
...

Having troubles w/functions and arrays

I'm Using Visual studio (C++) in a class that I am taking, I've had to teach myself functions, and I've hit a small snag in the road that I'd appreciate some advice on.
What I'm having trouble with, is the part of the assignment that states i must
"Utilize a function that prints (not find) the largest/average/smallest commissions"
The way I read this, I'm assuming she only wants it to print, and not do calculations in the function.
A friend suggested I try void print(etc) However I'm unsure how to grab the calculation in main and give it to the function I'm trying to print, or am i going at it all wrong?
I've commented out the portion of code I was trying to function. You can also find it at the very bottom of the code.
Any suggestions/help is greatly appreciated, as most of what I've looked up haven't really dealt with this problem (that I've found)
#include <iostream>
#include <iomanip>
using namespace std;
#define TITLE "Alva's"
#define STANDARD 0.05
#define HYBRID 0.10
#define ELECTRIC 0.15
#define HOLD 50
void dashLine();
int getSalesId();
int runProgram();
char vehicleType();
double sellingPrice();
void print(double largeSmallAverage);
int main()
{
int tot_count,
id_num[HOLD], //* ID
r_ay = 0, //* array
s_count, //*standard
h_count, //*Hybrid
e_count, //*electric
hold_id, //*array Id
compare, //*Pass
change, //*change made when change has value
yesno;
double tot_standard,
tot_hybrid,
tot_electric,
tot_price,
price[HOLD],
hold_price, //*Array hold
comm_l, //* Large
comm_s, //* Small
hold_comm, //*Array hold
avg_comm,
tot_commission,
commission[HOLD];
char car[HOLD],
temp_car;
tot_count = 0;
s_count = 0;
h_count = 0;
e_count = 0;
tot_price = 0;
tot_standard = 0;
tot_hybrid = 0;
tot_electric = 0;
cout << "\n" << TITLE << " Commission Calculator";
yesno = runProgram();
while (yesno == 1)
{
dashLine();
id_num[r_ay] = getSalesId();
car[r_ay] = vehicleType();
price[r_ay] = sellingPrice();
tot_price += price[r_ay];
switch (car[r_ay])
{
case 'S':
case 's':
commission[r_ay] = (price[r_ay] * STANDARD);
tot_standard += commission[r_ay];
s_count++;
break;
case 'H':
case 'h':
commission[r_ay] = (price[r_ay] * HYBRID);
tot_hybrid += commission[r_ay];
h_count++;
break;
case 'E':
case 'e':
commission[r_ay] = (price[r_ay] * ELECTRIC);
tot_electric += commission[r_ay];
e_count++;
break;
}
cout << "\n The commission for this sale, for Employee ID: " << fixed << setprecision(0) << id_num[r_ay] << " is:$ " << fixed << setw(5) << setprecision(2) << commission[r_ay];
cout << "\n";
yesno = runProgram();
r_ay++;
if (r_ay >= HOLD)
yesno = 0;
}
tot_count = (s_count + h_count + e_count);
tot_commission = (tot_standard + tot_hybrid + tot_electric);
{
cout << "\n Number of standard vehicle commissions calculated = " << fixed << setw(8) << setprecision(0) << s_count;
cout << "\n Number of hybrid vehicle commissions calculated = " << fixed << setw(8) << h_count;
cout << "\n Number of electric vehicle commissions calculated = " << fixed << setw(8) << e_count;
cout << "\n Number of vehicle commissions calculated = " << fixed << setw(8) << tot_count;
cout << "\n Total Overall price calculated =$ " << fixed << setw(8) << setprecision(2) << tot_price;
cout << "\n Total amount of standard vehicle commissions =$ " << fixed << setw(8) << tot_standard;
cout << "\n Total amount of hybrid vehicle commissions =$ " << fixed << setw(8) << tot_hybrid;
cout << "\n Total amount of electric vehicle commissions =$ " << fixed << setw(8) << tot_electric;
cout << "\n Total amount of all commissions paid out =$ " << fixed << setw(8) << tot_commission;
cout << "\n";
cout << "\n " << "Sales ID " << "Car type " << "Selling price " << "Commission ";
for (r_ay = 0; r_ay < tot_count; r_ay++)
{
cout << "\n " << fixed << id_num[r_ay] << " " << setprecision(2) << car[r_ay] << " " << setw(10) << price[r_ay] << " " << setw(10) << commission[r_ay];
}
if (tot_count > 0)
{
avg_comm = (tot_commission / tot_count);
comm_s = commission[0];
comm_l = commission[0];
for (r_ay = 1; r_ay < tot_count; r_ay++)
{
if (commission[r_ay] < comm_s)
comm_s = commission[r_ay];
if (commission[r_ay] > comm_l)
comm_l = commission[r_ay];
}
void print(double largeSmallAverage);
//{
// cout << "\n ";
// cout << "\n The smallest commission computed totals =$ " << fixed << setw(10) << comm_s;
// cout << "\n The largest commission computed totals =$ " << fixed << setw(10) << comm_l;
// cout << "\n Total average of commissions computed =$ " << fixed << setw(10) << avg_comm;
//}
}
cout << "\n";
change = 1;
compare = tot_count - 1;
do
{
change = 0;
for (r_ay = 0; r_ay < compare; r_ay++)
{
if (commission[r_ay] > commission[r_ay + 1])
{
temp_car = car[r_ay];
hold_id = id_num[r_ay];
hold_price = price[r_ay];
hold_comm = commission[r_ay];
commission[r_ay] = commission[r_ay + 1];
commission[r_ay + 1] = hold_comm;
id_num[r_ay] = id_num[r_ay + 1];
id_num[r_ay + 1] = hold_id;
car[r_ay] = car[r_ay + 1];
car[r_ay + 1] = temp_car;
price[r_ay] = price[r_ay + 1];
price[r_ay + 1] = hold_price;
change = 1;
}
}
compare--;
} while ((compare > 0) && (change == 1));
cout << "\n";
cout << "\n " << "Sales ID " << "Car type " << "Selling price " << "Commission ";
for (r_ay = 0; r_ay < tot_count; r_ay++)
{
cout << "\n " << fixed << id_num[r_ay] << " " << setprecision(2) << car[r_ay] << " " << setw(10) << price[r_ay] << " " << setw(10) << commission[r_ay];
cout << "\n ";
}
system("pause");
return 0;
}
}
void dashLine()
{
cout << "\n -----------------------------------";
}
int getSalesId()
{
int id_num;
cout << "\n Please enter Employee ID: ";
cin >> id_num;
while (id_num < 10000 || id_num > 99999)
{
cout << "\n Invalid Employee ID, Please enter a 5 digit ID ";
cin >> id_num;
}
return id_num;
}
int runProgram()
{
int rp_yesno;
cout << "\n Is there a customer? 1 = yes, 0 = no ";
cin >> rp_yesno;
while ((rp_yesno != 1) && (rp_yesno != 0))
{
cout << "\n Invalid Entry Please enter 1/0 ";
cout << "\n Is there a customer? 1 = yes 0 = no ";
cin >> rp_yesno;
}
return rp_yesno;
}
char vehicleType()
{
char car;
cout << "\n Please enter type of vehicle sold";
cout << "\n (S=standard, H=hybrid, E=electric): ";
cin >> car;
while (!((car == 'S') || (car == 's') || (car == 'h') || (car == 'H') || (car == 'E') || (car == 'e')))
{
cout << "\n Invalid input Please enter S/E/H ";
cin >> car;
}
return car;
}
double sellingPrice()
{
double price;
cout << "\n Please enter the selling price of the car:$ " << fixed << setprecision(2);
cin >> price;
while (price < 1)
{
cout << "\n Invalid entry, Please enter an amount greater than 0 ";
cin >> price;
}
return price;
}
void print(double largeSmallAverage)
{
double comm_s,
comm_l,
avg_comm;
{
cout << "\n ";
cout << "\n The smallest commission computed totals =$ " << fixed << setw(10) << comm_s;
cout << "\n The largest commission computed totals =$ " << fixed << setw(10) << comm_l;
cout << "\n Total average of commissions computed =$ " << fixed << setw(10) << avg_comm;
}
}
You would have a function called print that takes has three double parameters: void print(double small, double large, double average);.
Then later on you would call it with print(comm_s, comm_l, avg_comm);.
You need to change the definition of print:
void print(double small, double large, double average)
{
cout << "\n ";
cout << "\n The smallest commission computed totals =$ " << fixed << setw(10) << small;
cout << "\n The largest commission computed totals =$ " << fixed << setw(10) << large;
cout << "\n Total average of commissions computed =$ " << fixed << setw(10) << average;
}

How to get the sum of 3 columns of existing output using <iomanip>

I'v wrote a program for class which uses a for loop to have the user enter a values and it gives you a table with a loop counter, show number entered, and product. I'm trying to get the sum of All 10 numbers in each column to display at the end of each. I'm rather confused how to sum each column and display it underneath. Any help would be GREAT! I'm using Visual Studio Express 2012
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int input;
cout << "Enter Value: ";
cin >> input;
cout << "Loop Counter" << setw(20) << "Number Entered" << setw(14) << "Product" << endl;
for(int counter = 1; counter <= 10; counter++)
{
int product = input * counter;
if (product < 10 && counter != 10)
cout << setw(6) << counter << setw(17) << input << setw(17) << product << endl;
else if (product > 10 && counter != 10)
cout << setw(6) << counter << setw(17) << input << setw(18) << product << endl;
else
cout << setw(7) << counter << setw(16) << input << setw(18) << product << endl;
}
cout<<setfill('_')<<setw(45)<<"_"<<endl;
}
You'll need to sum up the column values in separate variables. Change your code like this:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int input = 0;
cout << "Enter Value: ";
cin >> input;
cout << "Loop Counter" << setw(20) << "Number Entered" << setw(14) << "Product" << endl;
int counterSum = 0;
int inputSum = 0;
int productSum = 0;
for(int counter = 1; counter <= 10; counter++) {
int product = input * counter;
if (product < 10 && counter != 10)
cout << setw(6) << counter << setw(17) << input << setw(17) << product << endl;
else if (product > 10 && counter != 10)
cout << setw(6) << counter << setw(17) << input << setw(18) << product << endl;
else
cout << setw(7) << counter << setw(16) << input << setw(18) << product << endl;
counterSum += counter;
inputSum += input;
productSum += product;
}
cout<<setfill('_')<<setw(45)<<"_"<<endl;
cout << setfill(' ') << setw(7) << counterSum << setw(16) << inputSum << setw(18) << productSum << endl;
}