Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Kaliemon

macrumors member
Apr 30, 2006
93
1
The way your functions are defined is invalid. The variables need to be defined when being used as parameters for the function. Also your check for the Sale ID only implemented after the first time the loop ran. Here is modified version of your code that is working. I added a few comments where the changes are not very drastic.

/*
* Pass6
*/

/* People get paid a base salary, plus a percentage of all sales over the base sales amount.
1) Read 3 digit salesman ID number, a float base salary and sales amount for each category.
2) Using a function, compute the commission earned in each category.
3) Print the ID number and base salary.
4) For each category, print description, sales amount, and commission amount.
5) Print total commission paid to the employee and total paid.
6) Continue looping until -999 is inputted for Salesman Number.
*/

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

/* Universal Floats */
float totalPcCom, totalMemCom, totalZipCom, totalPrintCom, baseSalary, pcSales, memCardSales, zipDriveSales, printerSales, totalCommission;

/* Function Prototype */
// No need for the line below as it is handled by the next function.
//double calcComm(float pcSales, float memCardSales, float zipDriveSales, float printerSales);

double calcCommission (float pcSales, float memCardSales, float zipDriveSales, float printerSales)

{
/* Check and see if salesman gets commission from PCs*
If so, commission is calculated. If not, commission
is left at zero. */
if (pcSales>=4000)
totalPcCom = (pcSales - 4000) * .10;
else
totalPcCom = 0;

/* Check and see about other commissions */
if (memCardSales>=1000)
totalMemCom = (memCardSales - 1000) * .05;
else
totalMemCom = 0;

if (zipDriveSales>=800)
totalZipCom = (zipDriveSales - 800) * .04;
else
totalZipCom = 0;

if (printerSales>=2000)
totalPrintCom = (printerSales - 2000) * .08;
else
totalPrintCom = 0;

return (totalPcCom, totalMemCom, totalZipCom, totalPrintCom);
}


int main ()
{

/* Everything has to be in a loop!!!! */
int salesID;
do
{
/* Output for 3 digit salesman ID number, float base salary and sales amount for each category. */
cout << "Please Enter Salesman ID number or -999 to terminate: " << endl;
cin >> salesID;
if (salesID == -999)
break;
cout << "Please Enter Base Salary: " << endl;
cin >> baseSalary;
cout << "Please Enter Personal Computer Sales: " << endl;
cin >> pcSales;
cout << "Please Enter Memory Card Sales: " << endl;
cin >> memCardSales;
cout << "Please Enter Zip Drive Sales: " << endl;
cin >> zipDriveSales;
cout << "Please Enter Printer Sales: " << endl;
cin >> printerSales;

/* Function and Computation Time!!! */
//Call the calcCommission function instead of calcComm
totalCommission = calcCommission (pcSales, memCardSales, zipDriveSales, printerSales);

/* Displaying the information for the current salesman */
cout << "Saleman ID # " << salesID << endl;
cout << "Base Salary: " << baseSalary << endl;
cout << "Total PC Commission: " << totalPcCom << endl;
}

/* Checking again if id!=-999 */
while (salesID!=-999);
}
 

sixstorm

macrumors regular
Original poster
Jan 16, 2006
212
0
Nashville, TN
Thanks for the replies everyone. Sorry I haven't responded quicker. Here is another one for ya. I'm writing a program that basically displays a menu (see menu function) and the user has to select one letter from the menu. On whichever letter is selected, it will access a function. Here is the code:

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

// Function Prototypes
void bestbuy(float val1, float val2, float val3);
void discountresults(float price, float discount);
void howmany(float amount, float costperitem);
void menu(string selection);

int main()
{
string selection;
float val1, val2, val3, price, discount, amount, costperitem;
// Bring up Menu from menu function
menu(selection);
// While "q" is not selected . . .
while(selection!="q")
{
cin >> selection;
if(selection=="b")
bestbuy(val1, val2, val3);
else if(selection=="d")
discountresults(price, discount);
else if(selection=="h")
howmany(amount, costperitem);
else
return 0;
}
}

void menu(string selection)
{
cout << "(B)est Buy Calculation" << endl;
cout << "(D)iscount Calculation" << endl;
cout << "(H)ow Many Calculation" << endl;
cout << "(Q)uit" << endl;
cout << endl;
cout << "Please Enter The Option (B, D, H or Q): ";
}

void bestbuy(float val1, float val2, float val3)

{
float number, minimum;
cout << "Please Enter 3 Prices: ";
cin >> val1 >> val2 >> val3;
// Find minimum price
if(val1>val2&&val2<val3)
minimum = val2;
else if (val1>val3&&val3<val2)
minimum = val3;
else if (val3>val1&&val1<val2)
minimum = val1;
else
minimum = 0;
// Find number of price
if(minimum==val1)
number = 1;
else if(minimum==val2)
number = 2;
else if(minimum==val3)
number = 3;
else
number = 0;
}

void discountresults(float price, float discount)

{
float total;
cout << "Please Enter a Price and the Discount Amount: ";
cin >> price >> discount;
total = price * (discount + 1);
cout << "The discount amount is " << discount << " the discounted price is " << total;
}

void howmany(float amount, float costperitem)

{
float amount, costperitem, numberitems, remainder;
cout << "Please Enter Amount Available and Cost of Each Item: ";
cin >> amount >> costperitem;
numberitems = amount / costperitem;
remainder = amount%costperitem;
cout << "You can buy " << numberitems << " and have " << remainder << " left over." << endl;
}

There are a few errors on here from XCode but I wanted to check with people here on a few things. Take a look at the first few lines in int main(). Will that code access the menu that's in the function? Also, does everything else look legit?
 

Soulstorm

macrumors 68000
Feb 1, 2005
1,887
1
For start, please use code tags, which formats the code and supports identation. It will be easier to read your code that way.

Secondly, see the howmany function:

Code:
void howmany(float amount, float costperitem)

{

	float amount, costperitem, numberitems, remainder;
	cout << "Please Enter Amount Available and Cost of Each Item: ";
	cin >> amount >> costperitem;
	numberitems = amount / costperitem;
	remainder = amount%costperitem;
	cout << "You can buy " << numberitems << " and have " << remainder << " left over." << endl;
}

Those are your errors in this function:
1) the "howmany" word is typedefed by another part of the C++ standard libraries. Don't ask me what part that is, I don't know. I just pressed the "escape" key and Xcode showed me that this word is typedef-ed. Change it to something different
2) You have declared the variables "amount" and "costperitem" twice. Why have you done that, and why do you want to 'cin' the "amount" and costperitem, since you have already passed their values as arguments to the function?

When you correct those mistakes, others will come up, you'll see. I didn't do it for you, since if I do, I will need to change the entire way you have done your exercise, and that wouldn't be appropriate. The only thing I can say is that using string comparisons just to select a function is inelegant and inefficient. it may cause you problems afterwards. I would do it with integers.

Also, a do...while loop would be best here. Define the integer outside the loop. And inside the 'do' loop, have it take a value by the user. Then, do whatever you want with it, and at the end of the loop, you should put something like '(while choice != 0)' ... That way you ensure that the statements inside the loop will at least be ran once.
 

sixstorm

macrumors regular
Original poster
Jan 16, 2006
212
0
Nashville, TN
Thanks for the help man. Our teacher decided to give us a hint or two and that lead to redesigning all the functions and stuff. I guess I was trying to have JUST the functions inside main() and then have the functions do the rest. Guess you can't do it that way huh? I'm debugging and tweaking right now so I'll be back I'm sure. Thanks again.
 

sixstorm

macrumors regular
Original poster
Jan 16, 2006
212
0
Nashville, TN
Haha, it's me again. I don't really need help with code for this one, but I just don't understand the concept of streaming information from text files. The biggest thing that I don't get is that when you have a text file filled with people's name, numbers, information, etc and you are using ifstream in a program to read from that file, how does the computer know what is what? I've got a program that will be doing exactly this; the text file has a nice layout of all the info mentioned above and I have to make a program to display all that info to the screen.

To clarify my question, let's look at cout. To display info to the monitor, you use cout right? cout << data; You tell the computer what to display very generally. If you are displaying multiple data items from a text file, how would you get specific information, such as JUST the customer's name or JUST the customer's number?

In one of my example programs, a teacher uses a program that reads from a text file which contains the number of students (header file, I know), grades from test 1 and grades from test 2. In my textbook, here is how it has the "input":

scores_in >> score1 >> score2;

Now how does the program know what test score is score 1? Score 2? This is what I'm trying to figure out. Sorry for the long post but I really needed to explain myself and see if anyone knows what I'm talking about. Any suggestions will help. Thanks!
 

steelphantom

macrumors 6502a
Oct 15, 2005
555
1
In one of my example programs, a teacher uses a program that reads from a text file which contains the number of students (header file, I know), grades from test 1 and grades from test 2. In my textbook, here is how it has the "input":

scores_in >> score1 >> score2;

Now how does the program know what test score is score 1? Score 2? This is what I'm trying to figure out. Sorry for the long post but I really needed to explain myself and see if anyone knows what I'm talking about. Any suggestions will help. Thanks!

The way that this particular example works is that data values in the input stream are broken up by spaces. So, if your text file contained "75 90" in it, scores_in would read 75 for score1 and 90 for score2. That was probably a horrible explanation, but I hope it helps at least a little bit. :eek:
 

sixstorm

macrumors regular
Original poster
Jan 16, 2006
212
0
Nashville, TN
The way that this particular example works is that data values in the input stream are broken up by spaces. So, if your text file contained "75 90" in it, scores_in would read 75 for score1 and 90 for score2. That was probably a horrible explanation, but I hope it helps at least a little bit. :eek:

That does make sense and helps out a pretty good amount. Thanks! Any other suggestions?
 

sixstorm

macrumors regular
Original poster
Jan 16, 2006
212
0
Nashville, TN
Alright here is my project. Let me know what you think. I don't really have a way of testing it out but it builds just fine in XCode. Here it is:

EDIT: Sorry for the look of the format. I copied straight from XCode onto here and it changed things to make it look nasty. Sorry!

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


int main ()
{
// Reads the following information from an external text file named "customer.dat", terminating with EOF check.
// Customer Number -> Int
// Customer Name -> String (Use getline)
// Beginning Balance -> Float
// Credit Card Charges -> Float
// Amount Paid -> Float
// Finance Charges -> Float

int customerNumber;
string customerName;
float begBal, creditCharges, amtPaid, finCharges, currentBal, howMany;

ifstream custom_in;
ofstream sum_out;

// Opens the "customer.dat" file.
custom_in.open("customer.dat");
assert(!custom_in.fail());
sum_out.open("summary.dat");
assert(!sum_out.fail());

howMany = 0;

// Display all the information to the screen, as well as current balance (beginning balance+credit card charges+
// amount paid+finanace charges).
while(!custom_in.eof())
{
// Get information from "customer.dat" and into the program.
custom_in >> customerNumber;
getline (custom_in, customerName);
custom_in >> begBal >> creditCharges >> amtPaid >> finCharges;
currentBal = begBal + creditCharges + amtPaid + finCharges;
// Total all appropriate columns and tell how many customers there were.
cout << customerNumber << " " << customerName << " " << begBal << " $" << creditCharges << " $" << amtPaid << " $" << finCharges << " $" << currentBal;
howMany += 1;
cout << "The total number of customers is " << howMany << endl;
// Create a new file "summary.dat" that contains Customer Number, Name and Current Balance.
// Writing into a new file called "summary.dat"
sum_out << customerNumber << endl;
sum_out << customerName << endl;
sum_out << currentBal << endl;
custom_in >> ws;
}
custom_in.close();
sum_out.close();

return 0;
}
 

LtRammstein

macrumors 6502a
Jun 20, 2006
570
0
Denver, CO
Well, for one, your howMany data will print out every time, only incremented at the end of each loop. You can also rewrite that as:

++howMany

This does howMany += 1 only it doesn't have to copy the memory slot again, or store any extra assignment operators. So, in a sense, it's faster.

Also, you split between your declared istream and ostream names. I found a cout in there that shouldn't be in there unless you want the user to see it. Even then, it should be after the while loop.

Other than that I don't see anything wrong with it.

A way to test the code is to create a .dat file in your project folder with information stored in it. Remember to not put any delimitors between data. The istream in this context:

cin >> data1 >> data2 >> data 3;

The istream already defines a space in a text file being a delimitor. If there is a deliminitor, like a semicolon, it will think it's apart of the data and continue on and then throw a run-time error.

Finally, it would look nicer if you indented your code. It hurts my eyes trying to run the code in my head and not seeing any indents.
 

sixstorm

macrumors regular
Original poster
Jan 16, 2006
212
0
Nashville, TN
Also, you split between your declared istream and ostream names.

What do you mean by split? I'm guessing not in the right order?

I found a cout in there that shouldn't be in there unless you want the user to see it. Even then, it should be after the while loop.

I'll take a look for that one. Everything should be shown just like it's say in the comments.

Finally, it would look nicer if you indented your code. It hurts my eyes trying to run the code in my head and not seeing any indents.

Well, I copied the stuff straight from XCode but when I clicked "Post", it automatically formatted it this way, sorry. I put a disclaimer!!! :D Thanks for your help man.
 

sixstorm

macrumors regular
Original poster
Jan 16, 2006
212
0
Nashville, TN
Got the last project of the semester . . . and I have no clue about this crap. It's about arrays and vectors. Here is my code with a program explaination included. Sorry about the indentation, blame it on the message boards. I copy and paste :D

#include <iostream>
#include <iomanip>
#include <vector>
#include <fstream>
#include <string>
#include <cassert>

const int MAXSTUDENTS = 101;

void get_data(vector<int>& ssNumber, vector<string>& studentName, vector<float>& GPA);
void print_out(vector<int>& ssNumber, vector<string>& studentName, vector<float>& GPA);


/* This program starts out reading from an external file 'Students.dat", terminates with EOF and stores the records in 3 separate
arrays. Assume that there are up to 100 students in the file. */

/* Social Security Number (Int)
Student Name (String)
GPA (Float)
*/

/* Display everything properly with column headings IN REVERSE ORDER!!! At the end, give the total # of students and the avg GPA. */

int main ()
{
vector<int>& ssNumber(MAXSTUDENTS);
vector<string>& studentName(MAXSTUDENTS);
vector<float>& GPA(MAXSTUDENTS);
float avg;
int totalStudents;

return 0;
}

void get_data(vector<int>& ssNumber, vector<string>& studentName, vector<float>& GPA)
{
ifstream students_in;
students_in.open("STUDENTS.DAT");
assert(!students_in.fail());
int size;

size = 0;
while(students_in >> ws && !students_in.eof())
{
students_in >> ssNumber[size];
getline (students_in, studentName[size]);
students_in >> GPA[size];
size++;
}
}

void print_out(vector<int>& ssNumber, vector<string>& studentName, vector<float>& GPA)
{
int size;
for(i=size; i>=0; i--)
cout << ssNumber[size] << ' ';
cout endl;
}

I know there are prolly a thousand things wrong with it, but I have no idea why. I'm following syntax rules to the tee but I'm still getting errors. Thanks in advance. I actually need a response tonight cuz it's due at midnight ahhh!!! Oh well, it wouldn't hurt to turn in a crappy project, I have a good grade. But I'd still like to learn this stuff!
 

Xavier

macrumors demi-god
Mar 23, 2006
2,829
1,610
Columbus
I dunno, just look at your C++ GUI Programming Guide, that might help :)

(I know nothing about C++, but the new mac ad was funny)
 

SamMiller0

macrumors member
Aug 17, 2004
66
0
San Jose, CA
I know there are prolly a thousand things wrong with it, but I have no idea why. I'm following syntax rules to the tee but I'm still getting errors.

For starters, please post the errors you encounter when compiling. After a quick glance at your code, I noticed you will need to bring in a couple things from the std namespace:

Code:
using std::vector;
using std::ifstream
using std::cout;
using std::endl;
 

savar

macrumors 68000
Jun 6, 2003
1,950
0
District of Columbia
hmm, well, it compiles fine with the if/else command in xCode, however the text I have on c++ mentions no such command. Also, when taking c++ classes, we always used if statements. Perhaps it's just personal preference of my professors. Oh well, I learn something new every day....this time from a self proclaimed "noob" :p :D

It's definitely a standard feature of the langauge. Any language that didn't have such a contruct would never get mainstream traction.

By the way, two if statements is different than an if-else statement, even if the two conditions in the former case are mutually exclusive and exhaustive: if-else compiles to one branch, where as "if-if" compiles to two.

You should always use if-else, never "if-if", if for no other reasons than clarity and maintainability.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.