C++ OOP not storing and displaying content correctly - c++

I am trying to create a program that takes input from the user about the length, width, and height of a box, and sends it to the appropriate member function and returns it back to the main. My length, width, and height are not storing and displaying themselves correctly in my OOP using Visual Studio. The code seems to take my last input (which is height) and set it to Length, and set the rest to 1.0. I can't figure out what im doing wrong here.
My GiftWrap.h file
#ifndef GIFTWRAP_H
#define GIFTWRAP_H
using namespace std;
class GiftWrap{
private:
double length;
double width;
double height;
double taxRate;
double pricePerInch;
double subTotal;
double total;
double tax;
public:
GiftWrap();
GiftWrap(double, double);
bool setLength(double);
bool setWidth(double);
bool setHeight(double);
bool setTaxRate(double);
bool setPricePerInch(double);
double getLength() const;
double getWidth() const;
double getHeight() const;
double getPriceperInch() const;
double getTaxRate() const;
double calcSubTotal();
double calcTax();
double calcTotal();
};
#endif
My GiftWrap.cpp file:
#include "GiftWrap.h"
#include <iostream>
using namespace std;
GiftWrap::GiftWrap(){
length = 1.0;
height = 1.0;
width = 1.0;
pricePerInch = 0.0036;
taxRate = 0.08;
}
GiftWrap::GiftWrap(double r, double c){
length = 1.0;
height = 1.0;
width = 1.0;
setPricePerInch(r);
setTaxRate(c);
}
double GiftWrap::getHeight() const{
return height;
}
double GiftWrap::getWidth() const{
return width;
}
double GiftWrap::getLength() const{
return length;
}
double GiftWrap::getPriceperInch() const{
return pricePerInch;
}
double GiftWrap::getTaxRate() const{
return taxRate;
}
double GiftWrap::calcSubTotal(){
subTotal = pricePerInch * ((2 * length * width) + (2 * length * height) + (2 * width * height));
return subTotal;
}
double GiftWrap::calcTax() {
tax = subTotal * taxRate;
return tax;
}
double GiftWrap::calcTotal() {
total = tax + subTotal;
return total;
}
bool GiftWrap::setHeight(double h){
if (h > 0){
height = h;
return true;
}
else{
return false;
}
}
bool GiftWrap::setWidth(double w){
if (w > 0){
width = w;
return true;
}
else{
return false;
}
}
bool GiftWrap::setLength(double l){
if (l > 0){
length = l;
return true;
}
else{
return false;
}
}
bool GiftWrap::setTaxRate(double t){
if (t > 0 && t < 1){
taxRate = t;
return true;
}
else{
return false;
}
}
bool GiftWrap::setPricePerInch(double p){
if (p > 0){
pricePerInch = p;
return true;
}
else{
return false;
}
}
My GiftWrapApp.cpp file:
#include "GiftWrap.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void showInvoice(GiftWrap&);
int main(){
char selection;
double len;
double wid;
double hei;
string storeName = "Sallys Gifts";
GiftWrap sallys(0.0025, 0.925);
do{
cout << "GIFT WRAP INVOICE GENERATOR" << endl
<< "------------------------------" << endl
<< "a)Generate Gift Wrap Invoice" << endl
<< "q)Quit" << endl;
cin >> selection;
if (selection == 'a' || selection == 'A'){
cout << "Please enter the length of your box:" << endl;
cin >> len;
while (!sallys.setLength(len)){
cout << "Invalid Selection, try again" << endl;
cin >> len;
}
cout << "Please enter the width of your box:" << endl;
cin >> wid;
while (!sallys.setLength(wid)){
cout << "Invalid Selection, try again" << endl;
cin >> wid;
}
cout << "Please enter the height of your box:" << endl;
cin >> hei;
while (!sallys.setLength(hei)){
cout << "Invalid Selection, try again" << endl;
cin >> hei;
}
cout << "\nGIFT WRAP INVOICE - " << storeName << endl
<< "----------------------------------" << endl;
showInvoice(sallys);
}
else if (selection == 'q' || selection == 'Q'){
cout << "Thank you for using this program!" << endl;
}
else{
cout << "Invalid Selection, try again" << endl;
}
} while (selection != 'q' && selection != 'Q');
system("PAUSE");
return 0;
}
void showInvoice(GiftWrap& r){
cout << "Box Length: " << fixed << setprecision(2) << r.getLength() << endl;
cout << "Box width: " << fixed << setprecision(2) << r.getWidth() << endl;
cout << "Box Height: " << fixed << setprecision(2) << r.getHeight() << endl;
cout << "Price Per Inch: " << fixed << setprecision(4) << r.getPriceperInch() << "\n" << endl;
cout << "Subtotal: " << fixed << setprecision(2) << r.calcSubTotal() << endl;
cout << "Tax: " << fixed << setprecision(2) << r.calcTax() << endl;
cout << setw(5) << "----------" << endl;
cout << "TOTAL: " << fixed << setprecision(2) << r.calcTotal() << endl;
cout << endl;
}
here is the result that im getting:
http://s10.postimg.org/q97jhgc4p/11111.png

In GiftWrapApp.cpp inside the do while() loop, there a two mistakes:
cout << "Please enter the width of your box:" << endl;
cin >> wid;
while (!sallys.setLength(wid)){ // <----- Should be sallys.setWidthd()!!!
cout << "Invalid Selection, try again" << endl;
cin >> wid;
}
cout << "Please enter the height of your box:" << endl;
cin >> hei;
while (!sallys.setLength(hei)){ // <-- Should be sallys.setHight(hei)!!
cout << "Invalid Selection, try again" << endl;
cin >> hei;
}
Hope this helps!

Related

C++ Incrementing Object Counter and Multiple Object Creation Issue

I was wondering if someone could help me on figuring out how to create multiple structs and also counting the number of structs created.
My Code follows three blocks, header file, Television file and then the main file.
Television.h
#include <iostream>
#include <string>
using namespace std;
class Televison {
string Manufacturer;
string Type; //Plasma, LCD
string Model; //Smart, regular
string Connection; //HDMI, VGA
string Power;
double Price;
int Serial_Number;
int Screen_size;
int Resolution; //larger one, so 1920 and etc.
int Channel; //any number
int Volume; //0 - 100
public:
//constructor
Televison(string Manufacturer, string Type, string Model, string Connection, string Power, double Price, int Serial_number, int Screen_size, int Resolution, int Channel, int Volume);
//Destructor
~Televison();
//Accessor Methods
string get_Manufacturer();
string get_Type();
string get_Model();
string get_Connection();
string get_Power();
double get_Price();
int get_Serial_Number();
int get_Screen_size();
int get_Resolution();
int get_Channel();
int get_Volume();
//mutator methods
string input_Manufacturer(string Manufacturer);
string input_Type(string Type);
string input_Model(string Model);
string input_Connection(string Connection);
string input_Power(string Power);
double input_Price(double Price);
int input_Serial_Number(int Serial_Number);
int input_Screen_size(int Screen_size);
int input_Resolution(int Resolution);
int input_Channel(int Channel);
int input_Volume(int Volume);
string change_Power(string Power);
int change_Channel(int Channel);
int change_Volume(int Volume);
};
static int num_tel = 1; //number of Televisons that will be incremented
Television.cpp
#include <iostream>
#include <string>
#include "Televison.h"
using namespace std;
//constructor
Televison::Televison(string Manufacturer, string Type, string Model, string Connection, string Power, double Price, int Serial_number, int Screen_size, int Resolution, int Channel, int Volume) {
this->Manufacturer = Manufacturer;
this->Type = Type;
this->Model = Model;
this->Connection = Connection;
this->Power = Power;
this->Price = Price;
this->Serial_Number = Serial_Number;
this->Screen_size = Screen_size;
this->Resolution = Resolution;
this->Channel = Channel;
this->Volume = Volume;
num_tel++;
// initiliazes the variables to default values
Manufacturer = "Sony";
Type = "Smart";
Model = "Plasma";
Connection = "HDMI";
Power = "ON";
Serial_Number = 1234;
Price = 199.00;
Screen_size = 50;
Resolution = 1440;
Channel = 100;
Volume = 100;
}
//Destructor
Televison::~Televison() {
cout << "The " << Manufacturer << " " << Model << " has finished shutting down." << endl;
num_tel--;
cout << "The inventory of television is now: " << num_tel << endl;
}
//Get Methods
string Televison::get_Manufacturer() {
return Manufacturer;
}
string Televison::get_Model() {
return Model;
}
string Televison::get_Type() {
return Type;
}
int Televison::get_Serial_Number() {
return Serial_Number;
}
string Televison::get_Connection() {
return Connection;
}
string Televison::get_Power() {
return Power;
}
double Televison::get_Price() {
return Price;
}
int Televison::get_Screen_size() {
return Screen_size;
}
int Televison::get_Resolution() {
return Resolution;
}
int Televison::get_Channel() {
return Channel;
}
int Televison::get_Volume() {
return Volume;
}
//mutator methods
int Televison::change_Channel(int Channel1) {
if (Channel > 0)
{
Channel = Channel1;
return Channel;
}
else
{
cout << "Invalid Channel, please enter another number" << endl;
return Channel;
}
}
int Televison::change_Volume(int Volume1) {
if (Volume1 > 0)
{
Volume = Volume1;
return Volume;
}
else
{
cout << "Invalid volume, please enter another number" << endl;
return Volume;
}
}
string Televison::change_Power(string Power1) {
if (Power1 =="Y")
{
Power = Power1;
return Power;
}
else
{
return Power;
}
}
string Televison::input_Connection(string Connection1) {
Connection = Connection1;
return Connection;
}
string Televison::input_Type(string M) {
Type = M;
return Type;
}
string Televison::input_Manufacturer(string M) {
Manufacturer = M;
return Manufacturer;
}
/*
string Televison::Manufacturer_code(string M,string N) {
string J = M.substr(0,4);
string Manufacturer_code = J + N;
return Manufacturer_code;
}
*/
string Televison::input_Model(string M) {
Model = M;
return Model;
}
string Televison::input_Power(string M) {
Power = M;
return Power;
}
double Televison::input_Price(double M) {
Price = M;
return Price;
}
int Televison::input_Serial_Number(int M) {
Serial_Number = M;
return Serial_Number;
}
int Televison::input_Screen_size(int M) {
Screen_size = M;
return Screen_size;
}
int Televison::input_Resolution(int M) {
Resolution = M;
return Resolution;
}
int Televison::input_Channel(int M) {
Channel = M;
return Channel;
}
int Televison::input_Volume(int M) {
Volume = M;
return Volume;
}
Source.cpp
#include <iostream>
#include <string>
#include "Televison.h"
using namespace std;
void displayStatus(Televison& Televison) {
cout << "Inventory of Televisons: " << num_tel << endl;
cout << "The Televison serial number: " << Televison.get_Serial_Number() << " " << Televison.get_Manufacturer() << " " << Televison.get_Model() << " " << Televison.get_Type() << " with " << Televison.get_Connection() << " ";
cout << "\n with " << Televison.get_Power() << " " << Televison.get_Price() << " with " << Televison.get_Screen_size() << " screen size " << Televison.get_Resolution() << "p " << "with " << Televison.get_Channel() << " channel " << Televison.get_Volume() << " Volume " << endl;
}
int main() {
{
Televison Televison_1("Sony", "Smart", "Plasma", "HDMI", "ON", 199.00, 1234, 50, 1440, 100, 100); //default Televison
cout << "This is the Televison program for personal Televison: " << endl;
bool repeat = true;
do {
cout << "Please enter the Manufacturer for the Televison: " << endl;
string Manufacturer;
getline(cin, Manufacturer);
int M1 = Manufacturer.length();
if (M1 < 1)
{
cout << "No input, please try again" << endl;
repeat = false;
}
else
repeat = true;
Televison_1.input_Manufacturer(Manufacturer);
} while (!repeat);
repeat = true;
do {
cout << "Please enter the Type of the Televison: " << endl;
string Type;
getline(cin, Type);
int M3 = Type.length();
if (M3 < 1)
{
cout << "No input, please try again" << endl;
repeat = false;
}
else
repeat = true;
Televison_1.input_Type(Type);
} while (!repeat);
repeat = true;
do {
cout << "Please enter the Model for the Televison: " << endl;
string Model;
getline(cin, Model);
int M2 = Model.length();
if (M2 < 1)
{
cout << "No input, please try again" << endl;
repeat = false;
}
else
repeat = true;
Televison_1.input_Model(Model);
} while (!repeat);
cout << "Please enter the Connection for the Televison: " << endl;
string Connection;
cin >> Connection;
Televison_1.input_Connection(Connection);
cout << "Enter the Serial Number: " << endl;
int inp4;
cin >> inp4;
Televison_1.input_Serial_Number(inp4);
cout << "Enter the Screen size: " << endl;
cin >> inp4;
Televison_1.input_Screen_size(inp4);
cout << "Enter the Resolution: " << endl;
cin >> inp4;
Televison_1.input_Resolution(inp4);
int a = 0;
while (a < 1)
{
cout << "Please enter the Price for the Televison: " << endl;
double Price;
cin >> Price;
if (Price > 0) //address speed must be greater than 0
{
Televison_1.input_Price(Price);
a++;
}
else
cout << "Invalid, enter again." << endl;
}
displayStatus(Televison_1);
int b = 0;
while (b < 1)
{
cout << "Would you like to Power your Televison? (Y/N)" << endl;
char input1;
cin >> input1;
if (input1 == 'Y' || input1 == 'y')
{
Televison_1.change_Power("ON");
b++;
}
else if (input1 == 'N' || input1 == 'n')
{
Televison_1.change_Power("OFF");
b++;
}
else
cout << "Invalid, enter again." << endl;
}
displayStatus(Televison_1);
int n = 0;
int n1 = 0;
while (n < 1)
{
cout << "Would you like to change any of the following attributes of your Televison? (Y/N)";
string input2, input3;
int input4;
double input5;
cin >> input2;
if (input2 == "Y" || input2 == "y")
{
while (n1 < 1) {
cout << "Which Televison attribute would you like to change? (Enter the respective number): " << endl;
cout << "1: Manufacturer" << endl;
cout << "2: Type" << endl;
cout << "3: Model" << endl;
cout << "4: Serial Number" << endl;
cout << "5: Connection" << endl;
cout << "6: Power" << endl;
cout << "7: Channel" << endl;
cout << "8: Screen size" << endl;
cout << "9: Resolution" << endl;
cout << "10: Volume" << endl;
cout << "11: Price" << endl;
int choice;
cin >> choice;
bool repeat1 = true;
bool repeat2 = true;
bool repeat3 = true;
switch (choice)
{
case 1:
cout << "Enter the Manufacturer: " << endl;
cin >> input3;
Televison_1.input_Manufacturer(input3);
break;
case 2:
cout << "Enter the Type: " << endl;
cin >> input3;
Televison_1.input_Type(input3);
break;
case 3:
cout << "Enter the Model: " << endl;
cin >> input3;
Televison_1.input_Model(input3);
break;
case 4:
cout << "Enter the Serial Number: " << endl;
cin >> input4;
Televison_1.input_Serial_Number(input4);
break;
case 5:
cout << "Enter the Connection: " << endl;
cin >> input3;
Televison_1.input_Connection(input3);
break;
case 6:
cout << "Enter the power: " << endl;
cin >> input3;
Televison_1.input_Power(input3);
break;
case 7:
cout << "Enter the Channel " << endl;
cin >> input4;
Televison_1.input_Channel(input4);
break;
case 8:
cout << "Enter the Screen size: " << endl;
cin >> input4;
Televison_1.input_Screen_size(input4);
break;
case 9:
do {
cout << "Enter the Resolution: " << endl;
cin >> input4;
if (input4 < 0)
{
cout << "Please enter a speed above 0" << endl;
repeat1 = false;
}
else
{
Televison_1.input_Resolution(input4);
repeat1 = true;
}
} while (!repeat1);
break;
case 10:
do {
cout << "Enter the Volume: " << endl;
cin >> input4;
if (input4 >= 0) {
cout << "Please enter a valid volume" << endl;
repeat2 = false;
}
else
{
repeat2 = true;
Televison_1.change_Volume(input4);
}
} while (!repeat2);
break;
case 11:
do {
cout << "Enter the Price: " << endl;
cin >> input5;
if (input5 > 0)
{
Televison_1.input_Price(input5);
repeat3 = true;
}
else
{
cout << "Please enter a valid price" << endl;
repeat3 = false;
}
} while (!repeat3);
break;
}
displayStatus(Televison_1);
cout << "Would you like to change another attribute? (Y/N)" << endl;
cin >> input3;
if (input3 == "Y" || input3 == "y")
{
}
else
n1++;
}
n++;
}
else if (input2 == "N" || input2 == "n")
{
cout << "The Televison will begin to shut down." << endl;
n++;
displayStatus(Televison_1);
}
else
cout << "Invalid, enter again." << endl;
}
}
// object goes out of scope - the destructor which shuts down the Televison
system("pause");
return 0;
}
Basically, my code only allows me to create one object and modify it. However, I would like to add the ability to create multiple objects and have a counter for it. I tried adding a counter, but it seems that doesn't work very well... I don't need someone to solve it, but if someone could point me to the right direction, that would be great.

Function that Stores the value from each iteration and then totals them

So I am trying to write a program that takes the total cost of a set of books given a certain value and then loop back to the beginning in order to get the total of a new set of books until the user tells it to stop. At the end of the program a total of the total cost of all books will be displayed. I am stuck trying to write this, thanks for any help with this, and sorry for my messy code as I am still learning.
Code Listed Here:
#include <iostream>
using namespace std;
const float kReqNew = 0.90;
const float kReqOld = 0.65;
const float kOptNew = 0.40;
const float kOptOld = 0.20;
class Book {
private:
float singleCost_;
int NeworOld_;
int ReqorOpt_;
int TotalBooksNeeded_;
int BookNumber_;
int NumOnHand_;
int prospectiveEnrole;
double totalCost_;
public:
void buildData();
void determineBooks();
void totalCosts();
void layOut();
void totalCostAdd();
};
void Book::buildData() {
cout << "Please enter: " << endl;
cout << "Book Number:";
cin >> BookNumber_;
cout << "Book Price: ";
cin >> singleCost_;
cout << "How many are in stock: ";
cin >> NumOnHand_;
cout << "Prospective Enrolment: ";
cin >> prospectiveEnrole;
cout << "Required(1), Optional(0)";
cin >> ReqorOpt_;
cout << "New(1), Old(0): ";
cin >> NeworOld_;
}
void Book::determineBooks(){
if(NeworOld_ == 1 && ReqorOpt_ == 1){
TotalBooksNeeded_ = NumOnHand_ * kReqNew;
}
else if(NeworOld_ == 1 && ReqorOpt_ == 0){
TotalBooksNeeded_ = NumOnHand_ * kOptNew;
}
else if(NeworOld_ == 0 && ReqorOpt_ == 1){
TotalBooksNeeded_ = NumOnHand_ * kReqOld;
}
else if(NeworOld_ == 0 && ReqorOpt_ == 0){
TotalBooksNeeded_ = NumOnHand_ * kOptOld;
}
cout << "Total Number of Books Needed: " << "$" << TotalBooksNeeded_ << endl;
}
void Book::totalCosts(){
totalCost_ = TotalBooksNeeded_ * singleCost_;
cout << "The total cost of the books is: " << totalCost_ << endl;
}
void Book::layOut(){
cout << BookNumber_<<endl;
cout << "$" << singleCost_ << endl;
cout << NumOnHand_ << endl;
}
void Book::totalCostAdd(){
double* newTotalCost;
*newTotalCost += totalCost_;
cout << newTotalCost << endl;
}
int main() {
Book books;
int exitNum;
cout << "\t\t\t ****************\n" << "\t\t\t Book Calculator\n" << "\t\t\t ****************\n";
do{
cout << "*******************************************\n";
books.buildData();
cout << "*******************************************\n";
books.layOut();
cout << "*******************************************\n";
books.determineBooks();
books.totalCosts();
cout << "*******************************************\n";
cout << "Would you like to continue: Yes(1), No(0)" << endl;
cin >> exitNum;
cout << "*******************************************\n";
books.totalCostAdd();
} while(exitNum != 0);
}
Thanks again for any help.

How to get grade average and do a search method?

I have been working on this project for days now and I got most of it down however there are three problems that I am having. I am trying to calculate the average grade from a ifstream file, the program reads it successfully however when I pass the array from one function to another, it just displays 0 and F as I am trying to display the percentage and letter grade.
My second question is how do I get the array to only print out elements that are populated. So if I create an array of 10 and only populate the first three elements, how would I got to only get those first three elements to print only?
And my other question is when I try doing a search, it keeps saying record not found even I typed the name correctly. The record is being search by last name.
Any pointers or help would be greatly appreciated. Thanks!
My code:
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <conio.h>
using namespace std;
void greeting(string[], string[], double[], double[], double[], int);
int getinfo(string[], string[], double[], double[], double[], int);
int calculateaverageandgrade(string[], string[], double[], double[], double [], int);
void sortandsearch(string[], string[], double[], double[], double[], int);
void goodbye(string[], string[], double[], double[], double[]);
int main() {
string fname[10] = { "" };
string lname[10] = { "" };
double grade[10] = { 0 };
double grade2[10] = { 0 };
double grade3[10] = { 0 };
const int arraysize = 10;
greeting(fname, lname, grade, grade2, grade3, arraysize);
getinfo(fname, lname, grade, grade2, grade3, arraysize);
calculateaverageandgrade(fname, lname, grade, grade2, grade3, arraysize);
system("pause");
return 0;
}
void greeting(string fname[], string lname[], double grade[], double grade2 [], double grade3[], int arraysize) {
int choice = int();
char cont = 'y';
while (cont == 'y' || cont == 'Y')
{
cout << setw(60) << "Main Menu" << endl;
cout << setw(66) << "======================" << endl;
cout << "\t\t\t\tToday we will be calculating grades from a file" << endl << "\t\t\t\tthat you can provide for us using notepad." << endl << "\t\t\t\tBe sure to update your file every time you run the program" << endl;
cout << endl;
cout << setw(64) << "Reading file...." << endl;
cout << setw(66) << "======================" << endl;
cout << endl << endl << endl;
cout << setw(65) << "1. Calculate Grades." << endl;
cout << setw(63) << "2. Search Grades" << endl;
cout << setw(68) << "2. Exit from the Program." << endl;
cout << endl;
cout << setw(70) << "Please Enter your Selection: ";
cin >> choice;
if (cin.fail())
{
cout << "Invalid selection" << endl;
cin.clear();
cin.ignore(1000, '\n');
}
else
{
if (choice == 1)
{
calculateaverageandgrade(fname, lname, grade, grade2, grade3, arraysize);
}
else if (choice == 2) {
sortandsearch(fname, lname, grade, grade2, grade3, arraysize);
}
else if (choice == 3)
{
goodbye(fname, lname, grade, grade2, grade3);
}
else
{
cout << "Invalid Selection!" << endl;
}
}
cout << "\nDo you want to continue (Y/N)....";
cin >> cont;
}
}
int getinfo(string fname[], string lname[],double grade[], double grade2[], double grade3[], int arraysize) {
system("cls");
ifstream in;
in.open("data.txt");
int i = 0;
while (!in.eof()) {
in >> fname[i] >> lname[i] >> grade[i] >> grade2[i] >> grade3 [i];
++i;
}
arraysize = i;
return arraysize;
}
int calculateaverageandgrade(string fname[], string lname[], double grade[], double grade2[], double grade3[], int arraysize) {
system("cls");
const int i = 10;
double total[i];
for (int a = 0; a < arraysize; ++a) {
cout << "Name:" << setw(20) << "Score: " << setw(20) << "Grade: " << endl;;
cout << fname[a] << " " << lname[a];
total[a] = grade[a] + grade2[a] + grade3[a];
total[a] = total[a] / 3;
cout << setw(20) << total[a] << endl;
if (total[a] >= 90) {
cout << setw(40) << "A" << endl;
}
else if (total[a] >= 80) {
cout << setw(41) << "B" << endl;
}
else if(total[a] >= 70) {
cout << setw(41) << "C" << endl;
}
else if (total[a] >= 60) {
cout << setw(41) << "D" << endl;
}
else {
cout << setw(41) << "F" << endl;
}
}
system("pause");
return total[i];
}
void sortandsearch(string fname[], string lname[], double grade[], double grade2[], double grade3[], int arraysize) {
system("cls");
string nameSearch = string();
int i = int();
bool flag = false;
char key = char();
system("cls");
cout << "\nEnter Name to be Searched: ";
cin >> nameSearch;
while (i<arraysize)
{
if (lname[i] == nameSearch)
{
cout << "Record Found --- ";
cout << "Record # " << i + 1 << " contains " << nameSearch << "'s information." << endl;
flag = true;
}
++i;
}
if (flag == false)
{
cout << "\nRecord Not Found!" << endl;
}
cout << "\n\n\nPress any Key to Continue...";
key = _getch();
}
void goodbye(string fname[], string lname[], double grade[], double grade2[], double grade3[]) {
system("cls");
cout << setw(70) << "Thanks for using my program!" << endl;
system("pause");
exit(1);
}

switch cases not opening, getting choice through return on a menu function

I am having trouble using a switch inside a do-while loop. menu is displaying, but after selection it is just displaying the menu again rather than opening up the proper switch case. and help would be greatly appreciated. I have tried looking for help and could not seem to find much.
#include <iostream>
using namespace std;
//function prototypes
int DisplayMenu(); //shows menu and returns input
double CalcAreaCircle(double radius ); //returns the area of the circle
double CalcAreaRectangle(double length, double width ); //returns the area of a rectangle
double CalcAreaTriangle(double base, double height ); //returns the area of a triangle
int Choice;
double AreaOfCircle;
double radius;
double AreaOfRectangle;
double length;
double width;
double AreaOfTriangle;
double base;
double height;
//function main
int main()
{
Choice = -1;
while (Choice != 4)
{
Choice = DisplayMenu();
switch (Choice)
{
case '1':
{
cout << "What is the radius of the circle?" << endl;
cin >> radius;
cout << endl;
AreaOfCircle = CalcAreaCircle(radius);
cout << endl << "The area of your circle is " << AreaOfCircle << endl;
break;
}
case '2':
{
cout << "what is the length of the rectangle?" << endl;
cin >> length;
cout << endl << "What is the width of the rectangle?" << endl;
cin >> width;
cout << endl;
AreaOfRectangle = CalcAreaRectangle(length, width);
cout << endl << "The area of your rectangle is " << AreaOfRectangle << endl;
break;
}
case '3':
{
cout << "What is the base of the triangle?" << endl;
cin >> base;
cout << endl << "What is the height of the triangle?" << endl;
cin >> height;
cout << endl;
AreaOfTriangle = CalcAreaTriangle(base, height);
cout << endl << "The area of your triangle is " << AreaOfTriangle << endl;
break;
}
}
}
system ("pause");
return 0;
}
//function DisplayMenu
int DisplayMenu()
{
int selection;
cout << "What would you like to know the area of?" << endl;
cout << "\t1. Area of a Circle." << endl;
cout << "\t2. Area of a Rectangle." << endl;
cout << "\t3. Area of a Triangle." << endl;
cout << "\t4. Quit." << endl;
cin >> selection;
while (selection < 1 || selection > 4)
{
cout << "Please enter a valid option." << endl;
cin >> selection;
cout << endl;
}
return selection;
}
//function CalcAreaCircle
double CalcAreaCircle(double radius)
{
double area;
const double PI = 3.14159;
area = PI * (area * area);
return area;
}
//function CalcAreaRectangle
double CalcAreaRectangle(double length, double width)
{
double area;
area = length * width;
return area;
}
//function CalcAreaTriangle
double CalcAreaTriangle(double base, double height)
{
double area;
area = base * height;
return area;
}
DisplayMenu() returns int. But your case statements are using char literals. When comparing char to int, it uses the character's code, e.g. case '1': is equivalent case 49:. Change your cases to use integer literals.
case 1:
and so on.

How can I initialize the structure variable that is already being passed?

Okay so we have to change this program from reading input from a user to reading it off of a file, and so far i have changed a good chunk of the code that will read off of the file but every time i go to run the code i get these 5 errors that I can't figure out so here is my code
// Author:
// Source file:
// Description:
// Compiler used:
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
struct records
{
int code;
double amount;
};
// Function Prototypes
void displayTitle();
double getBegBal(ifstream&);
void displayBal(records);
records getData(ifstream&);
double processCheck(double, double);
double processDeposit(double, double);
double processATM(double, double);
double processSvcChg(double);
//Global Constants
const double CHARGE = 10,
ATMFEE = 2;
int main()
{
//Variable Declarations
int transCode;
double balance,
transAmt;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
records trans;
ifstream inFile;
inFile.open("c:\\checkIn.dat");
displayTitle();
balance = getBegBal(inFile);
getData(inFile);
while (!inFile.eof())
{
trans = getData(inFile);
switch (trans.code)
{
case 1: balance = processCheck(balance, trans.amount); break;
case 2: balance = processDeposit(balance, trans.amount); break;
case 3: balance = processATM(balance, trans.amount); break;
}
displayBal(trans);
if (balance < 0)
balance = processSvcChg(balance);
getData(inFile);
}
return 0;
}
void displayTitle()
{
cout << "\n Check Register\n\n";
}
double getBegBal(ifstream& inFile)
{
//double bal;
records balance;
cout << " Enter beginning balance ";
inFile >> balance.amount;
return balance.amount;
}
void displayBal(records balance)
{
cout << "\t\tBalance = $" << setw(10) << balance.amount;
}
records getData(ifstream& inFile)
{
records rec;
cout << "\n\n Enter transaction code (0 to exit) ";
inFile >> rec.code;
if (rec.code > 0)
{
cout << "\n Enter transaction amount ";
}
return rec;
}
double processCheck(double bal, double amt)
{
cout << "\n Check = " << setw(10) << amt;
return (bal - amt);
}
double processDeposit(double bal, double amt)
{
cout << "\n Deposit = " << setw(10) << amt;
return (bal + amt);
}
double processATM(double bal, double amt)
{
records trans;
cout << "\n ATM = " << setw(10) << trans.amount;
bal = bal - amt;
displayBal(trans);
bal = bal - ATMFEE;
cout << "\n ATM Fee = " << setw(10) << ATMFEE;
return (bal);
}
double processSvcChg(double bal)
{
records trans;
cout << "\n Service chg =" << setw(8) << CHARGE;
bal = bal - CHARGE;
displayBal(trans);
return (bal);
}
error #2-3 are here
int transCode;
double balance,
transAmt;
the error is saying 'transCode': unreferenced local variable and
'transAmt': unreferenced local variable
errors #4-5 are here
double processATM(double bal, double amt)
{
records trans;
cout << "\n ATM = " << setw(10) << trans.amount;
bal = bal - amt;
displayBal(trans);// the error points here saying that the variable trans is uninitialized
bal = bal - ATMFEE;
cout << "\n ATM Fee = " << setw(10) << ATMFEE;
return (bal);
}
double processSvcChg(double bal)
{
records trans;
cout << "\n Service chg =" << setw(8) << CHARGE;
bal = bal - CHARGE;
displayBal(trans); // the error points here saying that the variable trans is uninitialized
return (bal);
}
Please and thank you for your help!
You initialized width = 0; and passed it to getWidth(). Therefore, width % 2 != 0 is evaluated as false and the prompt in getWidth() won't be displayed.
getWidth() won't need any arguments unless your assignment requires it because it is intended to just read the width and rethrn it.
do statement is useful to evaluate condition after executing loop body once.
int getWidth()
{
int width = 0;
do {
cout << "Enter width " << endl;
cin >> width;
} while (width % 2 != 0);
return width;
}
Then, use getWidth() in main() function like this:
width = getWidth();
It's working for me.
int displayMenu();
void displaySquare(int width);
void displayTriangle(int width);
int getWidth();
void displayUpsideDownTriangle(int width);
void displayDiamond(int width);
int main()
{
int width, shapes;
do {
shapes = displayMenu();
width = 0;
switch (shapes)
{
case 1:
width = getWidth();
displaySquare(width);
break;
case 2:
width = getWidth();
displayTriangle(width);
break;
case 3:
width = getWidth();
displayUpsideDownTriangle(width);
break;
case 4:
width = getWidth();
displayDiamond(width);
break;
case -9:
cout << "End of Program " << endl;
default:
cout << "Please choose one of the shapes..." << endl;
}
} while (shapes != -9);
system("pause");
return 0;
}
//this function sets up the display for the user
int displayMenu() {
int shapes;
cout << "\n~~ Shape Display menu ~~ " << endl << endl;
cout << " 1....Square\n" <<
" 2....Triangle\n " <<
" 3....Upside Down triangle\n " <<
" 4....Diamond\n\n " <<
" -9....Exit Program " << endl;
cout << endl;
cout << " Make a selection " << endl;
cin >> shapes;
return shapes;
}
int getWidth()
{
int width = 1;
do {
if (width % 2 != 0)
{
cout << "Enter width " << endl;
cin >> width;
}
else
{
cout << "Please enter odd number only. \nEnter width " << endl;
cin >> width;
}
} while (width % 2 == 0);
return width;
}
void displaySquare(int width)
{
int rows, columns;
for (rows = 0; rows < width; ++rows)
{
for (columns = 0; columns < width; ++columns)
{
cout << "# ";
}
cout << endl;
}
}
void displayTriangle(int width)
{
int rows, Spacing, ColHashtag;
for (rows = 1; rows < width; rows++) //controls the rows
{
for (Spacing = (width - rows); Spacing >= 1; Spacing--) // spaces out the rows to make an isoceles triangle
{
cout << " ";
}
for (ColHashtag = 1; ColHashtag <= (rows * 2) - 1; ColHashtag++) //controls the columns
{
cout << "#";
}
cout << endl;
}
}
void displayUpsideDownTriangle(int width)
{
int rows, Columns, spacing;
//sets up the rows for the top
for ((rows = width - 1); rows >= 1; rows--)
{
for (Columns = 1; Columns <= width - rows; Columns++) // sets up the columns
{
cout << " "; // spaces out the symbols to make an isoceles triangle
}
for (spacing = 1; spacing <= 2 * rows - 1; spacing++)
{
cout << "#";
}
cout << endl;
}
}
void displayDiamond(int width)
{
displayTriangle(width);
displayUpsideDownTriangle(width);
}
replace int main() and getWidth() with this
int main()
{
int width, shapes,wt;
do {
cout << "Enter width " << endl;
cin >> width;
wt=getWidth(width);
if(wt!=0)
{
shapes = displayMenu();
}
else
{
shapes=-9;
}
switch (shapes)
{
case 1:
displaySquare(wt);
break;
case 2:
displayTriangle(wt);
break;
case 3:
displayUpsideDownTriangle(wt);
break;
case 4:
displayDiamond(wt);
break;
case -9:
cout << "End of Program " << endl;
break;
default:
cout << "Please choose one of the shapes..." << endl;
}
} while (shapes != -9);
system("pause");
return 0;
}
int getWidth(int width)
{
while (width % 2 != 0) {
cout << "Enter width " << endl;
cin >> width;
}
return width;
}