I'm currently building a function that has to do with a pharmacist's input and I was wondering if this was the proper way to construct it using else/if statements. Am I lacking in some parts? (I've been getting this one single "expected declaration of the '}'" error that's been driving me crazy and have been trying to fix it for the past hour or so but to no avail.)
I would love to hear your advice on the parts that I might be missing out.
I've also listed the location of the error in the code below.
Thank you so much!
void pharm_page()
{
int choice3;
char pharm_user[30];
char pharm_pass[30];
char ship, ship_choice;
bool value_found = true;
system ("pause");
cout << "\n --------Pharmacist Login-------";
cout << "\n\n Please enter your username: ";
cin >> pharm_user;
cout << "\n Please enter your password:";
cin >> pharm_pass;
if ((strcmp (pharm_user, USER1) == 0) &&
(strcmp (pharm_pass, USER1PASSWORD) == 0))
{
getchar();
system("pause");
cout << "\n";
cout << "Success! You will be redirected to the pharmacist page." << endl;
cout << "\n";
cout << "------------------ Pharmacist Page -----------------\n" << endl
<< "Press 1: Access Patient Records" << endl;
cin >> choice3;
if (choice3 == 1)
{
const int ship_WM = 8.00;
const int ship_EM = 12.00;
int patient_id;
bool value_found = true;
cout << "-------------- Enter patient ID : ";
cin >> patient_id;
cin.ignore();
for (int i = 0; i < SIZE_P; i++)
{
if (patient_id == pat[i].p_id)
{
cout << "Patient Name : " << pat[i].p_name << endl
<< "Patient ID : " << pat[i].p_id << endl
<< "Doctor Name : " << pat[i].p_doctor << endl
<< "Appointment Date : " << pat[i].p_date << endl
<< "Medicine Expiry Date : " << pat[i].expiry << endl
<< "Medicine Name : " << pat[i].med_name << endl
<< "Medicine Quantity : " << pat[i].med_q << endl
<< "Direction of Use : " << pat[i].direct << endl
<< "Patient's Address: " << pat[i].p_add << endl
<< "Continue prescription? " << pat[i].option << endl
<< "\n" << endl;
cout << "\t\t========================================================================================\n\n";
cout << "\t\tPlease take note that fridge items e.g. insulin, medication in liquid form e.g. syrup or \n";
cout << "\t\tlotion and pressurized canisters e.g. inhalers are not eligible for postage. Kindly \n";
cout << "\t\t\t\t\tsource at the nearest hospital/pharmacy.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n";
cout << "\t\t========================================================================================\n\n";
cout << "--------- State the method of pick-up for patient's medicine (Press A for 'Shipping' or B for 'Pick-up'): ";
cin >> ship;
if (toupper(ship) == 'A')
{
cout << "You have chosen to ship the medicine. Please enter the shipping zone of the patient to determine shipping charges. (EG: Press C for 'WM' or D for 'EM'): " << endl;
cin >> ship_choice;
if (toupper(ship_choice) == 'C')
{
for (int i = 0; i < 1; i++)
{
ofstream file_label("patient.txt");
if(file_label.is_open())
{
file_label << "Patient Name : " << pat[i].p_name << endl;
file_label << "Patient ID : " << pat[i].p_id << endl;
file_label << "Doctor Name : " << pat[i].p_doctor << endl;
file_label << "Appointment Date : " << pat[i].p_date << endl;
file_label << "Medicine Expiry Date : " << pat[i].expiry << endl;
file_label << "Medicine Name : " << pat[i].med_name << endl;
file_label << "Medicine Quantity : " << pat[i].med_q << endl;
file_label << "Direction of Use : " << pat[i].direct << endl;
file_label << "The medicine will be shipped to the patient's address at " << pat[i].p_add << "." << endl;
file_label << "Shipping charges: RM" << ship_WM << endl;
file_label.close();
cout << "\n" << endl;
break;
}
}
}
else if (toupper(ship_choice) == 'D')
{
for (int i = 0; i < 1; i++)
{
ofstream file_label("patient.txt");
if(file_label.is_open())
{
file_label << "Patient Name : " << pat[i].p_name << endl;
file_label << "Patient ID : " << pat[i].p_id << endl;
file_label << "Doctor Name : " << pat[i].p_doctor << endl;
file_label << "Appointment Date : " << pat[i].p_date << endl;
file_label << "Medicine Expiry Date : " << pat[i].expiry << endl;
file_label << "Medicine Name : " << pat[i].med_name << endl;
file_label << "Medicine Quantity : " << pat[i].med_q << endl;
file_label << "Direction of Use : " << pat[i].direct << endl;
file_label << "The medicine will be shipped to the patient's address at " << pat[i].p_add << "." << endl;
file_label << "Shipping charges: " << ship_EM << endl;
file_label.close();
cout << "\n" << endl;
break;
}
}
}
else
cout << "Unable to open file. Please try again once the program restarts.";
}
}
else if (toupper(ship) == 'B')
{
for (int i = 0; i < 1; i++)
{
ofstream file_label("patient.txt");
if(file_label.is_open())
{
file_label << "Patient Name : " << pat[i].p_name << endl;
file_label << "Patient ID : " << pat[i].p_id << endl;
file_label << "Doctor Name : " << pat[i].p_doctor << endl;
file_label << "Appointment Date : " << pat[i].p_date << endl;
file_label << "Medicine Expiry Date : " << pat[i].expiry << endl;
file_label << "Medicine Name : " << pat[i].med_name << endl;
file_label << "Medicine Quantity : " << pat[i].med_q << endl;
file_label << "Direction of Use : " << pat[i].direct << endl;
file_label << "The medicine will be shipped to the patient's address at " << pat[i].p_add << "." << endl;
file_label << "Shipping charges: None " << endl;
file_label.close();
cout << "\n" << endl;
break;
}
}
}
}
}
else
value_found = false;
}
if(value_found)
cout << "No record of patient in database. Please re-enter current patient's number and try again. ";
else
cout << "Wrong input. Please try again." << endl;
}
} <============================================================== (that one error is located here)
else
{
cout << "\n";
cout << "Your credentials are wrong. Please enter the right credentials once the program has been terminated." << endl;
}
}
}
A good base line is that if you have a function that is long enough for you not to see it in one page, you should generate sub-functions.
Another good base line is that if you can easily name a sub-segment of your code, you should consider making it another function.
If you see that you repeat nearly similar code several times, like your writing lines, it's time to refactor. Avoid repeating the same code all over.
Most important: C++ is an OOP language. Use it as one.
For example, take your lines
cout << "Patient Name : " << pat[i].p_name << endl
<< "Patient ID : " << pat[i].p_id << endl
<< "Doctor Name : " << pat[i].p_doctor << endl
<< "Appointment Date : " << pat[i].p_date << endl
<< "Medicine Expiry Date : " << pat[i].expiry << endl
<< "Medicine Name : " << pat[i].med_name << endl
<< "Medicine Quantity : " << pat[i].med_q << endl
<< "Direction of Use : " << pat[i].direct << endl
<< "Patient's Address: " << pat[i].p_add << endl
<< "Continue prescription? " << pat[i].option << endl
<< "\n" << endl;
I'm not sure what pat stores, but given that it has members, it's at least a structure. Now why does that structure or class not have a method like print() or to_string()? Which would reduce your lines above to
cout << path[i].to_string() << endl;
Do similar things in other parts where you print a lot of things and your code should be far better to read already. Note that a to_string() method suits well as that would also work with your ofstream.
Question, is that what you show us a function or a method? It should be the latter. You should have something like a class PharmacyInterface which has such functionality as methods. Basically every single access you can name should be a method. Something like accessing the data of a single patient should be a method. Entering the password (and storing a boolean that it was successfully entered) should be a method. All those methods should read very shortly and straight-forwarded.
Basically, for anything that you nest, ask yourself if you can easily name it. If so, make it it's own method.
As for your error, use a proper IDE. If you use auto-indentation, the line with the missing { or } will stick out, and maybe even be marked as bad. Also, you can check to which opening brace a closing brace belongs by clicking behind it, a good IDE will then indicate the opening brace.
But in general, if you have troubles finding an incorrect bracing, your code is simply too convoluted, and you should use what I wrote above.
Lastly, I strongly recommend that you put your code on CodeReview, another StackExchange website which concerns itself with coding style rather than fixing bugs like StackOverflow does.
Note that the code you post there will be ripped apart, and that is quite useful for you to learn things.
Edit: Another thing I noticed is that you have a for loop that searches for an ID. This creates an avoidable nesting. Instead, have another method (or function if you want to go procedural) called size_t patient_index_from_id(int id) or similar, which does the search. Saves you from one nesting and can be reused.
Related
Good day everyone. My program is about a Computer Shop (Laptop). So, people can buy laptop through this program and "PCPurchase" is the function that gonna handle the customer transaction.
I use file-pointer and struct to save information about all the laptops. And of course, the struct store more than 1 type of laptops because obviously this is a laptop shop.
I encounter a problem where user can only buy (enter name) of the first entry (first laptop) in the struct. Here: cout << "Enter the laptop company and name you want to buy: " << endl;
If customer enter the name of 2nd laptop,3rd and so on, it will jump to line
cout << endl << "\tNot available!" << endl; cout << "\tPress A to try again or B to return to main menu" << endl;
It indicates that the laptop's name is not in database which actually is.
Can I know what the problem here actually is?
int PCPurchase()
{
struct customer cust;
system("color 0A");
char laptop[100];
double total_bill;
const double TAX=0.06;
system("cls");
cout << setfill ('-') << setw (55) << "-" << endl;
cout << "\t\tCustomer Dashboard" << endl;
cout << setfill ('-') << setw (55) << "-" << endl;
fptr=fopen("laptop.txt","ab+");
cout << "Available laptops: " << endl;
rewind(fptr);
while(fread(&PC,sizeof(PC),1,fptr)==1)
{
cout << endl << "Laptop company and name: ";
cout << PC.laptopcompany << endl;
cout << "RAM: ";
cout << PC.RAM << endl;
cout << "Processor: ";
cout << PC.Processor << endl;
cout << "Price: RM";
cout << PC.price << endl;
}
cout << "\nPress any key to continue purchase" << endl;
getch();
fflush(stdin);
getInfo(cust); //get information of customer
cout << "Enter the laptop company and name you want to buy: " << endl;
cout << "(Type 'RETURN' if you do not want to purchase)" << endl << endl;
gets(laptop);
rewind(fptr);
while(fread(&PC,sizeof(PC),1,fptr)==1)
{
if(strcmpi(PC.laptopcompany,laptop)==0)
{
cout << setfill ('-') << setw (55) << "-" << endl;
cout << "\tYou have selected" << endl;
cout << setfill ('-') << setw (55) << "-" << endl;
cout << "Laptop company and name: ";
cout << PC.laptopcompany << endl;
cout << "RAM: ";
cout << PC.RAM << endl;
cout << "Processor: ";
cout << PC.Processor << endl;
cout << "Price: ";
cout << PC.price << endl;
total_bill=PC.price+(PC.price*TAX);
cout << setfill ('-') << setw (55) << "-" << endl;
cout << fixed << showpoint << setprecision (2);
cout << "Name: "<< cust.name << endl; // struct output
cout << "Email: "<< cust.email << endl;
cout << "Phone Number: " << cust.number << endl;
cout << "Your total bill (including 6% tax): RM" << total_bill << endl;
cout << setfill ('-') << setw (55) << "-" << endl;
cout << endl << "\tPress 1 to return to main screen!";
cout << endl << "\tPress 2 to quit the program!";
char afterpurchase;
afterpurchase=getche();
if (afterpurchase=='1')
{
fclose(fptr);
main();
}
else
exit_system();
}
else if(strcmpi("RETURN",laptop)==0)
main();
else
{
cout << endl << "\tNot available!" << endl;
cout << "\tPress A to try again or B to return to main menu" << endl;
char choice1;
choice1=getche();
choice1=toupper(choice1); // Transform to uppercase
switch (choice1)
{
case 'A': fclose(fptr);
PCPurchase();
break;
default : fclose(fptr);
main();
break;
}
}
}
}
It is because of else statement. If you want to buy the laptop from the second record of the data and so on, it will compare with the first record and will not return true. So, it will proceed to else statement and will not repeat the while loop. Simply change the else statement to make the loop working.
I'm printing a statement from classes using getter functions. The top 1.5 lines of my cout statement are not printing. I have tried flushing the stream, and I also copied and pasted the lines that are not printing outside the if statement, and it prints! I can't figure out what is going on. Here is the function:
// display all books out on loan
void displayBorrowed(vector<LibraryBook>& book)
{
cout << "Books currently checked out: " << endl << endl;
for(unsigned int i = 0; i < book.size(); i++)
{
//cout << "ID: " << book[i].getId_() << " Title: "
//<< book[i].getTitle_() << endl << endl;
if(book[i].getIsLoaned_() == true)
{
std::cout.flush();
cout << "ID: " << book[i].getId_() << " Title: "
<< book[i].getTitle_() << " Author: "
<< book[i].getAuthorFirst_() << " " << book[i].getAuthorLast_()
<< " Year Published: " << book[i].getYearPubl_() << endl
<< "Due Date: " << book[i].getDueMonth_() << "/"
<< book[i].getDueDay_() << "/" << book[i].getDueYear_()
<< " Date Borrowed: " << book[i].getBorrwdMonth_() << "/"
<< book[i].getBorrwdDay_() << "/" << book[i].getBorrwdYear_()
<< endl << "Checked out by: " << book[i].getBorrwFirst_()
<< " " << book[i].getBorrwLast_() << endl << endl;
}
}
}
It displays this:
Books currently checked out:
Author: Brendan Behan Year Published: 1958
Due Date: 8/2/2017 Date Borrowed: 7/21/2017
Checked out by: Cassie Peterson
If the lines in the if statement are copied out of the if statement it displays normally:
ID: 78620 Title: Zhuan Falun
I tried changing the if statement to false to display all the books not loaned, and they all displayed the same except for the very last book (number 50 finally displayed the id # and the title. I am at a complete loss. What is going on?
It should look like this:
ID: 78620 Title: Zhuan Falun Author: Brendan Behan Year Published: 1958
Due Date: 8/2/2017 Date Borrowed: 7/21/2017
Checked out by: Cassie Peterson
(havent formatted display yet)
I just changed it to this where I have every single element that doesn't display in its own cout statement, and NONE of it displays!! What??! (up until author, where it started displaying before, I mean.)
for(unsigned int i = 0; i < book.size(); i++)
{
if(book[i].getIsLoaned_() == true)
{
std::cout.flush();
cout << "ID: " ;
cout << book[i].getId_();
cout << " Title: ";
cout << book[i].getTitle_();
cout << " Author: "
<< book[i].getAuthorFirst_() << " " << book[i].getAuthorLast_()
<< " Year Published: " << book[i].getYearPubl_() << endl
<< "Due Date: " << book[i].getDueMonth_() << "/"
<< book[i].getDueDay_() << "/" << book[i].getDueYear_()
<< " Date Borrowed: " << book[i].getBorrwdMonth_() << "/"
<< book[i].getBorrwdDay_() << "/" << book[i].getBorrwdYear_()
<< endl << "Checked out by: " << book[i].getBorrwFirst_()
<< " " << book[i].getBorrwLast_() << endl << endl;
}
It prints when I put an endl at the end of each element:
if(book[i].getIsLoaned_() == true)
{
std::cout.flush();
cout << "ID: " << endl;
cout << book[i].getId_() << endl;
cout << " Title: " << endl;
cout << book[i].getTitle_() << endl;
cout << " Author: " << endl;
cout << book[i].getAuthorFirst_() << " " << book[i].getAuthorLast_() << endl;
cout << " Year Published: " << book[i].getYearPubl_() << endl;
cout << "Due Date: " << book[i].getDueMonth_() << "/" << endl;
cout << book[i].getDueDay_() << "/" << book[i].getDueYear_() << endl;
cout << " Date Borrowed: " << book[i].getBorrwdMonth_() << "/" << endl;
cout << book[i].getBorrwdDay_() << "/" << book[i].getBorrwdYear_() << endl;
cout << endl << "Checked out by: " << book[i].getBorrwFirst_() << endl;
cout << " " << book[i].getBorrwLast_() << endl << endl;
}
Books currently checked out:
ID:
47492
Title:
Borstal Boy
Author:
Brendan Behan
Year Published: 1958
Due Date: 8/
2/2017
Date Borrowed: 7/
21/2017
Checked out by: Cassie
Peterson
My suggestion:
Print each of the members in their own line.
Find out which member is problematic.
Dig deeper into the contents of the member to understand how it got there and fix it.
if(book[i].getIsLoaned_() == true)
{
std::cout.flush();
std::cout << "ID: " << book[i].getId_() << std::endl
<< "Title: " << book[i].getTitle_() << std::endl
<< "Author First: " << book[i].getAuthorFirst_() << std::endl
<< "Author Last:" << book[i].getAuthorLast_() << std::endl
<< "Year Published: " << book[i].getYearPubl_() << std::endl
<< "Due Date Month: " << book[i].getDueMonth_() << std::endl
<< "Due Date Day: " << book[i].getDueDay_() << std::endl
<< "Due Date Year: " << book[i].getDueYear_() << std::endl
<< "Borrowed Month: " << book[i].getBorrwdMonth_() << std::endl
<< "Borrowed Day: " << book[i].getBorrwdDay_() << std::endl
<< "Borrowed Year: " book[i].getBorrwdYear_() << std::endl
<< "Checked out by first: " << book[i].getBorrwFirst_() << std::endl
<< "Checked out by last: " << book[i].getBorrwLast_() << std::endl
<< std::endl;
}
}
/* Sometimes "half cout statement not printing problem" may occur due to use of dangling or dangerous pointers. In the code below all cout statements that present, after dangling pointer printing statement are not printing anything.
If we remove the dangling pointer's cout statement then everything will be fine.
code:
// dangling pointer is dangerous because it can hold undesired address. */
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a =5;
char b= 'a';
int *p = &a;
char *p1 =&b;
int *p3; // p3 is dangling pointer
cout<<"size of p "<<sizeof(p)<<endl; // o/p is 8, bcoz x64 bit compiler
gives 8byte and x32 gives 4 byte.
cout<<"size of p1 "<<sizeof(p1)<<endl;
cout<<"size of p3 "<<sizeof(p3)<<endl;
cout<<"address of p3 is "<<&p3<<endl;
cout<< "value at p3 is "<<*p3<<endl; //***dangling or dangerous pointer.***
cout<<"hello my name is rahul ";
cout<<a<<endl;
cout<<&a<<endl;
//cout<<*a<<endl; // shows error (invalid type argument)
cout<<p<<endl; // shows base address
cout<<&p<<endl; // shows pointers address
cout<<*p<<endl;
cout<<"this is an end"<<endl;
return 0;
}
I cannot seem to get the "full"
to display the concatenation of First and last.
It compiles but when I run it it will appear blank.
Can you tell me why?
Have tried to figure it our for hours.
Here are my declerations
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
#define tax 0.30
#define parking_deductions 10.00
#define overtime_hours 40
#define max_hours 60
#define max_pay 99
string namestring( string first, string last, string full);
I'm attempting to pass this module to my main
string namestring(string first, string last, string full)
{
//input name
cout << "What is your first name? " << endl;
cout << "first name: " << endl;
cin >> first;
cout << "What is your last name? " << endl;
cout << "last name: " << endl;
cin >> last;
//process name
full = last + " " + first;
return full;
}
By calling it like so
namestring(first, last, full );
Where I expect the full name input by the user to be displayed below
cout << left << fixed << " " << "Reg." << " " << " Ovt." << " Hourly" << " Net" << " " << " Gross" << endl;
cout << left << fixed << setprecision(2) << setw(10) << "Name " << " Hours" << " Hours" << " Rate" << " Pay" << " Taxes" << " Deduct" << " Pay" << endl;
cout << left << fixed << setprecision(2) << setw(10) << "====================" << " " << "=====" << " " << "=====" << " " << "=====" << " " << "======" << " " << "======" << " " << " " << "========" << " " << "=======" << endl;
cout << left << setprecision(2) << setw(20) << full << right << " " << right << setw(4) << hours << right << " " << right << overtime << " " << right << pay << " " << right << net_pay << " " << right << taxs << " " << right << parking_deductions << " " << right << gross_pay << right << endl;
cout << endl;
cout << endl;
I'm assuming the goal here is to get the following 3 strings,
First Name
Last Name
Full Name
To do this, you would need to pass the arguments by reference, not by value:
void namestring(string& first, string& last, string& full)
{
//input name
cout << "What is your first name? " << endl;
cout << "first name: " << endl;
cin >> first;
cout << "What is your last name? " << endl;
cout << "last name: " << endl;
cin >> last;
//process name
full = last + " " + first;;
}
There is also no need to return a string if you pass the "full" string by reference, since the function will fill it for you.
string namestring(string first, string last, string& full)
//input name
{
cout << "What is your first name? " << endl;
cout << "first name: " << endl;
cin >> first;
cout << "What is your last name? " << endl;
cout << "last name: " << endl;
cin >> last;
//process name
full = last + " " + first;
return full;
}
You are passing the full by value. So it's the local copy of the function which is modified. You need it to pass by reference.
If you also want the first and last value you also need to pass it by reference.
Basically I want an exact copy of the code that appears in the console window to also be outputted to a txt file..
#include <conio.h>
#include <iostream>
#include <dos.h>
#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
#include <fstream>
using namespace std;
//Initialising gotoxy Comand
void gotoxy(int col, int row)
{
COORD coord;
coord.X = col;
coord.Y = row;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
int main()
{
char name1[20], name2[20], name3[30], name4[20];
int funcNum = 0;
int n1Nv, n1Mv, n1SEv, n1SWv;
int n2Nv, n2Mv, n2SEv, n2SWv;
int n3Nv, n3Mv, n3SEv, n3SWv;
int n4Nv, n4Mv, n4SEv, n4SWv;
int n1Total, n2Total, n3Total, n4Total, perTotal;
double n1Per, n1PerTotal;
double n2Per, n2PerTotal;
double n3Per, n3PerTotal;
double n4Per, n4PerTotal;
double maxVote;
//Introduction
cout << "================================================================================";
cout << " Ballot Results" << endl;
cout << " Version 2.1" << endl;
cout << " Created by Team b0nkaz" << endl;
cout << "================================================================================" << endl;
//Candidate Identification
cout << "Enter the candidates running for president" << endl << endl;
//cin.getline (workaround,30); //**
cout << "Candidate One: ";
cin.getline (name1,20);
cout << "Candidate Two: ";
cin.getline (name2,20);
cout << "Candidate Three: ";
cin.getline (name3,20);
cout << "Candidate Four: ";
cin.getline (name4,20);
cout << " " << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
cout << "Input vote numbers from each region pressing enter after each input:" << endl << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
//Input Table
//Regions
gotoxy(22,19);
cout << "North" << endl;
gotoxy(31,19);
cout << "Midlands" << endl;
gotoxy(43,19);
cout << "South East" << endl;
gotoxy(57,19);
cout << "South West" << endl;
gotoxy(69,19);
cout << "| Total" << endl;
cout << "_____________________________________________________________________|__________" << endl;
gotoxy(69,21);
cout << "|";
gotoxy(69,22);
cout << "|";
gotoxy(69,23);
cout << "|";
gotoxy(69,24);
cout << "|";
gotoxy(69,25);
cout << "|";
gotoxy(69,25);
cout << "|";
gotoxy(69,26);
cout << "|";
gotoxy(69,27);
cout << "|";
gotoxy(69,28);
cout << "|";
gotoxy(69,29);
cout << "|";
//Candidates
gotoxy(0,22);
cout << name1;
gotoxy(0,24);
cout << name2;
gotoxy(0,26);
cout << name3;
gotoxy(0,28);
cout << name4;
//Equals
cout << endl;
cout << "_____________________________________________________________________|__________" << endl;
//Vote Input
//North
gotoxy(22,22);
cin >> n1Nv;
gotoxy(22,24);
cin >> n2Nv;
gotoxy(22,26);
cin >> n3Nv;
gotoxy(22,28);
cin >> n4Nv;
//Midlands
gotoxy(31,22);
cin >> n1Mv;
gotoxy(31,24);
cin >> n2Mv;
gotoxy(31,26);
cin >> n3Mv;
gotoxy(31,28);
cin >> n4Mv;
//South East
gotoxy(43,22);
cin >> n1SEv;
gotoxy(43,24);
cin >> n2SEv;
gotoxy(43,26);
cin >> n3SEv;
gotoxy(43,28);
cin >> n4SEv;
//South West
gotoxy(57,22);
cin >> n1SWv;
gotoxy(57,24);
cin >> n2SWv;
gotoxy(57,26);
cin >> n3SWv;
gotoxy(57,28);
cin >> n4SWv;
//Total Votes
//Name1
gotoxy(72,22);
n1Total = n1Nv + n1Mv + n1SEv + n1SWv;
cout << n1Total;
//Name2
gotoxy(72,24);
n2Total = n2Nv + n2Mv + n2SEv + n2SWv;
cout << n2Total;
//Name3
gotoxy(72,26);
n3Total = n3Nv + n3Mv + n3SEv + n3SWv;
cout << n3Total;
//Name4
gotoxy(72,28);
n4Total = n4Nv + n4Mv + n4SEv + n4SWv;
cout << n4Total << endl << endl << endl;
//Percentage Calculation
perTotal = n1Total + n2Total + n3Total + n4Total;
//Candidate One
n1Per = n1Total*100;
n1PerTotal = n1Per/perTotal;
//Candidate Two
n2Per = n2Total*100;
n2PerTotal = n2Per/perTotal;
//Candidate Three
n3Per = n3Total*100;
n3PerTotal = n3Per/perTotal;
//Candidate Four
n4Per = n4Total*100;
n4PerTotal = n4Per/perTotal;
cout << "Please wait for calculation..." << endl << endl;
//Spinning Loading Line
//std::cout << '-' << std::flush;
//for(;;)
//{
//Sleep(100);
//std::cout << "\b\\" << std::flush;
//Sleep(100);
//std::cout << "\b|" << std::flush;
//Sleep(100);
//std::cout << "\b/" << std::flush;
//Sleep(100);
//std::cout << "\b-" << std::flush;
//}
//Sleeping Program
Sleep(1500); //1.5 secs
//Total Output
cout << "Candidate percentage:" << endl << endl;
//Converting To One Decimal Place
cout << fixed;
std::cout.precision(1);
//Vote Percentages
cout << name1 << " = " << n1PerTotal << "%" << endl;
cout << name2 << " = " << n2PerTotal << "%" << endl;
cout << name3 << " = " << n3PerTotal << "%" << endl;
cout << name4 << " = " << n4PerTotal << "%" << endl << endl;;
//Calculating Winnner
maxVote=n1PerTotal;
if (n2PerTotal>maxVote)
maxVote=n2PerTotal;
if (n3PerTotal>maxVote)
maxVote=n3PerTotal;
if (n4PerTotal>maxVote)
maxVote=n4PerTotal;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
//Sleeping Program
Sleep(1500); //1.5 secs
if(maxVote==n1PerTotal)
{
cout << " ***********************************************************************" << endl;
cout << " " << name1 << " " << endl;
cout << " is the new president of The British Society of IT Professionals " << endl;
cout << " with " << n1PerTotal << "% of the vote " << endl;
cout << " ***********************************************************************" << endl << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
}
else if(maxVote==n2PerTotal)
{
cout << " ***********************************************************************" << endl;
cout << " " << name2 << " " << endl;
cout << " is the new president of The British Society of IT Professionals " << endl;
cout << " with " << n2PerTotal << "% of the vote " << endl;
cout << " ***********************************************************************" << endl << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
}
else if(maxVote==n3PerTotal)
{
cout << " ***********************************************************************" << endl;
cout << " " << name3 << " " << endl;
cout << " is the new president of The British Society of IT Professionals " << endl;
cout << " with " << n3PerTotal << "% of the vote " << endl;
cout << " ***********************************************************************" << endl << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
}
else if(maxVote==n4PerTotal)
{
cout << " ***********************************************************************" << endl;
cout << " " << name4 << " " << endl;
cout << " is the new president of The British Society of IT Professionals " << endl;
cout << " with " << n4PerTotal << "% of the vote " << endl;
cout << " ***********************************************************************" << endl << endl;;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
}
cout << "Press any key to exit..." << endl;
getch();
//system("pause");
}
I am using MS Visual Studio 2010 and any help would be great! Please note I am still very new to C++.
EDIT I would like to be able to see the output in CMD as well as have a separate txt file with the same output code. Everything that is displayed in the CMD window also copied into the txt file.
use an ofstream operator as such.
For some reason I can't seem to find the comment button or I would be involved in the discussion above... but I've edited my code below to reflect what seem to be some concerns of yours.
#include<fstream>
using namespace std;
int main()
{
ofstream fout;
fout.open("data.txt"); //Will create a new file if one is not already in existence
//You can put a static filename here or have them enter a string
//If you use a custom string your input will be "fout.open(STRING.c_str());
fout<<"Used exactly like cout from this point on";
fout.close(); //When you are done using it to close the file
}
I chose to name my ofstream operator fout because (while this is not always good to do) this way you can quickly change all of your cout's to fout's, or replicate them.
If the user enters a value and you want to spit it back out as well, you can use the ofstream operator after every cin.
You can find more information about ofstream here...
Hope this helped!
You can do this from outside of the application using tee. tee takes the output of a program and splits it into two streams (e.g. one to stdout and one to a file). Unfortunately, Windows doesn't come with a tee command but there are many implementations available.
If you want this to happen from within your program you can do the equivalent of tee using a custom ofstream. This article explains how.
My professor instructed us to make a Starbucks like menu where the user can continue to input orders until they are finished. I got the menu display down along with the loop, but I can't get it to add up the orders that were inputted and display a total.
#include <iostream>
using namespace std;
int main()
{
int choice = 1;
cout << endl << "Welcome to Hunterbucks!";
while (choice > 0)
{
cout << endl << "Input -1 when you're finished ordering!";
cout << endl << endl << "Coffee" << " " << "($)";
cout << endl << "1. Regular" << " " << "1.50";
cout << endl << "2. Decaf" << " " << "1.23";
cout << endl << "3. Americano" << " " << "2.25";
cout << endl << "4. Espresso" << " " << "2.25";
cout << endl << "5. Latte" << " " << "2.50";
cout << endl << "6. Cappuccino" << " " << "2.75";
cout << endl << "7. Frappuccino" << " " << "2.75";
cout << endl << "8. Macchiato" << " " << "2.50";
cout << endl << endl << "Snacks" << " " << "($)";
cout << endl << "9. Muffin" << " " << "1.00";
cout << endl << "10. Blueberry Muffin" << " " << "1.25";
cout << endl << "11. Raspberry Muffin" << " " << "1.25";
cout << endl << "12. Scone" << " " << "0.75";
cout << endl << "13. Blueberry Scone" << " " << "1.00";
cout << endl << "14. Croissant" << " " << "0.75";
cout << endl << endl << "What would you like to order? ";
cin >> choice;
if (choice <= 0)
cout << endl << "Thank you for your order.";
else
cout << endl << "What else would you like to order?";
}
cout << endl << "Thank you for choosing Hunterbucks! Come again soon.";
return 0;
}
Any info that can help me? I'm just a beginner and have been trying this for a few hours.
In pseudo-code you want something like this:
float total = 0.0;
while (choice > 0)
{
....
cin >> choice;
if (choice <= 0)
cout << endl << "Thank you for your order.";
else
{
total += costs[choice];
cout << endl << "What else would you like to order?";
}
}
You'll need to define an array names costs that contains the cost of each item. You'll also want to tackle validation of the user input so that you don't erroneously attempt to read outside the range of the costs array.
You're probably looking at something like this:
#include <iostream>
using namespace std;
int main()
{
int choice = 1;
float sum = 0.0;
float arr[] = {
0.00, 1.50, 1.23, 2.25, 2.25, 2.50, 2.75, 2.75, 2.50,
1.00, 1.25, 1.25, 0.75, 1.00, 0.75
};
cout << endl << "Welcome to Hunterbucks!";
while (choice > 0)
{
cout << endl << "Input -1 when you're finished ordering!";
cout << endl << endl << "Coffee" << " " << "($)";
cout << endl << "1. Regular" << " " << "1.50";
cout << endl << "2. Decaf" << " " << "1.23";
cout << endl << "3. Americano" << " " << "2.25";
cout << endl << "4. Espresso" << " " << "2.25";
cout << endl << "5. Latte" << " " << "2.50";
cout << endl << "6. Cappuccino" << " " << "2.75";
cout << endl << "7. Frappuccino" << " " << "2.75";
cout << endl << "8. Macchiato" << " " << "2.50";
cout << endl << endl << "Snacks" << " " << "($)";
cout << endl << "9. Muffin" << " " << "1.00";
cout << endl << "10. Blueberry Muffin" << " " << "1.25";
cout << endl << "11. Raspberry Muffin" << " " << "1.25";
cout << endl << "12. Scone" << " " << "0.75";
cout << endl << "13. Blueberry Scone" << " " << "1.00";
cout << endl << "14. Croissant" << " " << "0.75";
cout << endl << endl << "What would you like to order? ";
cin >> choice;
if (choice <= 0){
cout << endl << "Thank you for your order.";
} else {
cout << endl << "What else would you like to order?";
sum += arr[choice];
}
}
cout << "Total: " << sum << endl;
cout << endl << "Thank you for choosing Hunterbucks! Come again soon.";
return 0;
}
Do note the following:
1) Your menu choices being with '1' thus there is a need to offset your arr at index '0' with the '0.00' value there.
2) The cost added up follows that of your indexed array, thus you would probably want to format your output according to your array, so that next time, all you need to do is to update your array.
Hope it helped. Cheers!
The way you have your code set up warrants a switch statement, like the following:
double total = 0;
switch (choice)
{
case 1:
total += 1.50; // Regular.
break;
case 2:
total += 1.23; // Decaf.
break;
// Etc.
}
cout << endl << "Your total is " << total;
That being said, the easiest way to do this would be to have an array of prices:
double prices[] = {1.50, 1.23, 2.25};
// ...
total += prices[choice - 1]; // No switch statement needed.