n8thatsme 22 Light Poster

Ok, so here is what I did so far. Like I said I'm not used to vectors so its pretty new to me. When you said for me to create using new do you mean like this?

salariedEmployee = new Employee;
salariedEmployee = new SalariedEmployee;

As for the push_back command, I'm not sure how to use that. Here is my code. Do I create the new objects inside each case? If your wondering what the input will look like from the file it will be as follows.
S firstName lastName socialSecurityNumber weeklySalary birthdate
H firstName lastName socialSecurityNumber wage hours birthdate
C firstName lastName socialSecurityNumber grossSales commissionRate birthdate
B firstName lastName socialSecurityNumber grossSales commissionRate baseSalary birthdate

S Tom Smith 111-11-1111 800 09/10/1942
H Karen Price 222-22-2222 16.75 40 01/01/1982
C Sue Jones 333-33-3333 10000 .06 05/31/1980
B Bob Lewis 444-44-4444 5000 .04 300 10/04/1950

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <fstream>

// include definitions of classes in Employee hierarchy
#include "Date.h"
#include "Employee.h"
#include "SalariedEmployee.h" 
#include "HourlyEmployee.h"
#include "CommissionEmployee.h"  
#include "BasePlusCommissionEmployee.h" 
using namespace std;

int main()
{
   vector < Employee * > employees;
   string firstName;
   string lastName;
   string ssn;
   double salary;
   double hourlyWage;
   double hoursWorked;
   double sales;
   double rate;
   int    month;
   int    day;
   int    year;
   char   type;   
   fstream indata;                          // The file to be opened

   indata.open("employee.txt"); // Open the file to be read
   if(!indata) 
   { 
      cout << "Error: file could not be opened" << endl;
      exit(1);
   }

   do
   {
      indata>>type; …
n8thatsme 22 Light Poster

1. You can't declare a vector of references in C++ (it's the other story why). Fortunately, I see a vector of POINTERS in you snippet. Feel the difference ;)

Yeah I feel the difference lol.

2. Why pointers in that case? Better define std::vector<SalariedEmployee> . Take on trust: it's much more better for you ;)

I have to use Employee because it is the base class, so I can just use Employee instead of SalariedEmployee? Also, I didn't mention this but after my program has read in the file, it should go into a “query” mode. In this mode, it should prompt for a social security number to be located and the current month (as an integer). It should then search for a match of the SS number and retrieve the current earnings. In addition, if the employee’s birth month matches the current month, I will add a $100 birthday bonus to the earnings. Then I will display the employee’s name, birthdate, and earnings including any bonus. So I need to use pointers still correct?

3. What's a problem? Read a file with getline(ifstream,string) line by line, check up the 1st char (with switch or if, it's a matter of taste), then attach the line to istringstream and extract field by field to SalariedEmployee object members then push_back result into the vector. That's all...

Will this be different now that I've explained what I have to do after I read the file?

n8thatsme 22 Light Poster

I'm guessing this guy was a bad instructor perhaps? No, my instructor isn't Ron, his name is Terry and he was a Software Engineer for 27 years.

n8thatsme 22 Light Poster

Ok, I never really understood vectors and I have write a program that uses a vector of Employee references to store the company’s payroll. My program will load the payroll by reading a file (employee.dat) that contains one employee’s information per line. Each line of the file will begin with a letter (S for salaried, H for hourly, C for commission, or B for base plus commission.) The fields on the remainder of the line will depend on the first letter of the line and will be separated by spaces. I didn't think you could use a vector of references but here is the code. Also, I need to know how to read it in from a file and to use the appropriate object. Should I use switch statements or else ifs? Remember, its just modifying it.

#include <iostream>
using std::cout;
using std::endl;
using std::fixed;

#include <iomanip>
using std::setprecision;
  
#include <vector>
using std::vector;

// include definitions of classes in Employee hierarchy
#include "Employee.h"
#include "SalariedEmployee.h" 
#include "HourlyEmployee.h"
#include "CommissionEmployee.h"  
#include "BasePlusCommissionEmployee.h" 

int main()
{
   // create derived-class objects
   SalariedEmployee salariedEmployee( 
      "John", "Smith", "111-11-1111", 800 );
   HourlyEmployee hourlyEmployee( 
      "Karen", "Price", "222-22-2222", 16.75, 40 );
   CommissionEmployee commissionEmployee( 
      "Sue", "Jones", "333-33-3333", 10000, .06 );
   BasePlusCommissionEmployee basePlusCommissionEmployee( 
      "Bob", "Lewis", "444-44-4444", 5000, .04, 300 );

   // create vector of four base-class pointers
   vector < Employee * > employees( 4 );

   // initialize vector with Employees
   employees[ 0 ] = &salariedEmployee;
   employees[ 1 ] = &hourlyEmployee;
   employees[ 2 ] = &commissionEmployee;
   employees[ 3 ] = …
n8thatsme 22 Light Poster

This program should search for an invoice, display all its current information, and allow the user to change and store each of the values originally entered. To exit “edit mode” (and the program) the user can enter an Invoice Number of 0. My problem is I can't properly search through all the elements. I've tested it throughly and all my set and get functions are working properly, its my loop thats the problem. I've walked through this in my head, and verbally but I can't see whats wrong. I think my pride is getting in the way so I need help. Output given at the bottom.

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

#include "invoiceheader.h"

#define MAX_INVOICES 10000 
#define EXIT_CODE    0    
#define SKIP_CODE    1 
int main()
{
   Invoice *Invoices = new Invoice[MAX_INVOICES];
   int     invoiceNum;   
   int     qtyShipped;   
   int     partNum;      
   string  partDescrip; 
   float   unitPrice;   
   string  editChoice;   
   bool    done = true; 
   bool    found = true;

do
   {
      for(int i=0; i<MAX_INVOICES; i++)
      {
      cout << "\nType an Invoice number you would like to search for"
           << " or (" << EXIT_CODE << " to exit): ";
      cin  >> invoiceNum;

      // Check for the exit code
      if(invoiceNum == EXIT_CODE)
      {
         done = false;
         break;
      }
      else
      {
        
            if(invoiceNum == Invoices[i].getInvoiceNum())
            {
               cout << "\nDoes anything need editing? (y or n): ";
               cin  >> editChoice;
               if(editChoice == "y")
               {
                  cout << "\nCurrent contents of invoice " << invoiceNum
                       << ":";
                  Invoices[i].printInvoiceData();
                  cout << "\n\nEnter new quantity shipped (" << SKIP_CODE 
                       << " to …
n8thatsme 22 Light Poster

Fortunately, it's so simple: ;)

cin.ignore('\n'); // skip 10 chars: '\n' == 10

The 1st ignore() member function argument: The number of elements to skip from the current read position. That's why you have "or the engine" wreck only.
Change to

cin.ignore(1,'\n');

or study the Narue's Novel About cin Flushing (see Ancient Dragon's post)...

Thats exactly what I needed, thank you so much. So simple, all I needed was "1" lol. Thanks for all the help guys!

n8thatsme 22 Light Poster

So if I use getline it still skips over it. Also I only included the setPartDescription function definition to shorten the code. I hope this is enough information. I used the cin.ignore as well and if I type something like "This part is for the engine." the output in the program is "or the engine."

Header File:

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class Invoice
{
public:

          Invoice();

   void   setInvoiceNum(int invceNum);
   void   setQtyShipped(int qtyShip);
   void   setPartNum(int partNum);
   void   setPartDecription(string partDescrip);
   void   setUnitPrice(float untPrice);
   void   setSalesTaxRate(float salesTaxRte);
   void   setShippingCost(float shipCost);

   int    getInvoiceNum()     const {return invoiceNumber;}
   int    getQtyShipped()     const {return qtyShipped;}
   int    getPartNum()        const {return partNumber;}
   string getPartDecription()       {return partDescription;}
   float  getUnitPrice()      const {return unitPrice;}
   float  getSalesTaxRate()   const {return salesTaxRate;}
   float  getShippingCost()   const {return shippingCost;}

   float  calcSalesTaxAmnt();
   float  calcTotalCost();
   void   printInvoiceData();

private:
   int    invoiceNumber;
   int    qtyShipped;
   int    partNumber;
   string partDescription;
   float  unitPrice;
   float  salesTaxRate;
   float  salesTaxAmnt;
   float  shippingCost;
   float  totalCost;

};

void Invoice::setPartDecription(string partDescrip)
{
   partDescription = partDescrip;
}

Main Fuction:

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

#include "invoiceheader.h"

#define MAX_INVOICES 10000
#define EXIT_CODE    0

int main()
{
   Invoice *Invoices = new Invoice[MAX_INVOICES];
   int     invoiceNum;
   int     qtyShipped;
   int     partNum;
   string  partDescrip;
   float   unitPrice;
   string  editChoice;
   bool    done = true;


   do
   {
      for(int i=0; i<MAX_INVOICES; i++)
      {
         cout << "\nEnter an Invoice Number (or " << EXIT_CODE << " to exit):";
         cin  >> invoiceNum;
         if(invoiceNum == EXIT_CODE)
         {
            done = false;
            break;
         }
         else
         {
            Invoices[i].setInvoiceNum(invoiceNum);
            cout << Invoices[i].getInvoiceNum();  // debug
            cout << "\nEnter …
n8thatsme 22 Light Poster

Ok I have a simple question I have a header file that has the following code

void   setPartDecription(string partDescrip);
string getPartDecription()  {return partDescription;}

Of course I have other functions but these are the problem functions and they are public. In my main function I have this:

cout << "\nEnter Part Description: ";
cin  >> partDescrip;
Invoices[i].setPartDecription(partDescrip);
cout << Invoices[i].getPartDecription();

After I type in a part description like "This part is for the engine" it goes into an infinite loop. Is there a certain way I need to pass and return the string data type? I've tried

getline(cin, partDescrip);

but its just skips over it and doesn't even let me type a part description, help would be really appreciated.

n8thatsme 22 Light Poster

Ok so I prompt the user for invoices (Invoice Number, Quantity Shipped, Part Number, Part Description, and Unit Price) until the user gets tired and enters an Invoice Number of 0 for an invoice. After the user enters an Invoice Number of 0, he should not be prompted for any additional invoice info, and the program should enter an “edit mode”. In edit mode, the user is prompted for an invoice number. The program should search for that invoice, display all its current information, and allow the user to change and store each of the values originally entered. To exit “edit mode” (and the program) the user can enter an Invoice Number of 0.
Problem 1: My problem is trying to think of a way to exit the loop incase they enter 0 first or 0 anytime after the first. Am I doing it right with the do..while or is there some other way?
Problem 2: I'm trying to think of a good search algorithm, should I use sequential search?

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

#include "invoice.h"

#define MAX_INVOICES 10000
#define EXIT_CODE       0

int main()
{
   Invoice *Invoices = new Invoice[MAX_INVOICES];
   int    invoiceNum;
   int    qtyShipped;
   int    partNum;
   string partDescrip;
   float  unitPrice;
   bool   done = true;


   do
   {
      bool done = true;
      cout << "\nEnter an Invoice Number (or " << EXIT_CODE << " to exit):";
      cin  >> invoiceNum;
      if(invoiceNum == 0)
         done = false;
      for(int i=0; (i<MAX_INVOICES || done != false); i++)
      {
         cout << …
n8thatsme 22 Light Poster

Thats what it was. I've used strcpy_s but didn't know it would apply to all the other str functions. Thanks.

n8thatsme 22 Light Poster

I got this and it works well, but I get a warning.

Warning 2 warning C4996: 'strcat' was declared deprecated

char sentence[MAX_SENTENCE] = {0};
      strcat(sentence, article[rand() % MAX_ARTICLES]);
      strcat(sentence, " ");
      strcat(sentence, noun[rand() % MAX_NOUNS]);
      strcat(sentence, " ");
      strcat(sentence, verb[rand() % MAX_VERBS]);
      strcat(sentence, " ");
      strcat(sentence, preposition[rand() % MAX_PREPS]);
      strcat(sentence, " ");
      strcat(sentence, article[rand() % MAX_ARTICLES]);
      strcat(sentence, " ");
      strcat(sentence, noun[rand() % MAX_NOUNS]);
n8thatsme 22 Light Poster

That would be the way I would go because I hate char. But I need a way to do it without using string type.

n8thatsme 22 Light Poster

I tried something and this works nicely.

cout << article[rand() % MAX_ARTICLES];

Now that I got that fixed I have a problem. I'm gonna make an array called sentence that I want to add these random words to. Is there an easy function instead of strcat? I don't want to have to use strcat 15 times to I can concat the word then a space, word then a space etc.

n8thatsme 22 Light Poster

Ok well I have 4 char arrays. Each array has predefined words in them. For example:

char *article[MAX_ARTICLES] =
      { "the", "a", "one", "some", "every", "any" };

I'm trying to make random sentences as defined by the user. So if they type in the value 567 or whatever it may be I use it as the seed for srand. I'm trying to print whats in the value of the array. So if the word "every" was print it would need would need some seed value mod 6. I tried this

cout << article[srand(seed_val) % MAX_ARTICLES];

Just to test if I was accessing a random element but it was to no avail because its invalid syntax. Is there another way I can do this? I'm sure I can make variables and assign the new random value every time but I want to make this efficient. Any ideas?

n8thatsme 22 Light Poster

I messed around with it for the last couple hours and I got it to work. I thank everyone for there great help, it is really appreciated.

Thanks,
n8thatsme

n8thatsme 22 Light Poster

That did take out the continuous printing of no match. Now when I type a name that is in the file it doesn't display the info it just prompts me for another name, also if I type a name that is not in the file it prompts me for another name. When I type the EXIT_CODE it says No Match and just exits like its suppose to.

do
   {
       bool done = false;
       int  cntr    = 0;
       cout << "Enter first and last name (case sensative) of the employee"
	      << " you want to find: \n";
       cout << "Type " << EXIT_CODE << " to exit\n";
       getline(cin,info);

      while(cntr < MAX_EMPLOYEE_SIZE && !done)
	  {
	     full_name = EmployeeInfo[cntr].get_first_name() + " " 
			    + EmployeeInfo[cntr].get_last_name();
         if(info == full_name)
         {
            EmployeeInfo[cntr].display_info(); 
	    done = true;
         }
         cntr++;
      }
   }
   while(info != EXIT_CODE);

   if(done == true)
      cout << "Found" << endl; 
   else
      cout << "No match" << endl;
n8thatsme 22 Light Poster

Oh, I noticed the first its just Ive tried using the counter everywhere and it just keeps coming up No Match. I've tried it in all these places:

do
   {
       bool done = false;
       int  cntr    = 0;
       cout << "Enter first and last name (case sensative) of the employee"
	      << " you want to find: \n";
       cout << "Type " << EXIT_CODE << " to exit\n";
       getline(cin,info);

      while(cntr < MAX_EMPLOYEE_SIZE && !done)
	  {
		 // cntr++;
	     full_name = EmployeeInfo[cntr].get_first_name() + " " 
			    + EmployeeInfo[cntr].get_last_name();
		 //cntr++;
         if(info == full_name)
         {
			//cntr++;
            EmployeeInfo[cntr].display_info(); 
	        done = true;
			//cntr++;
         }
		 else
		 {
			 //cntr++;
			 cout << "No Match";
			 //cntr++;
		 }
		 //cntr++;
      }
   }
   while(info != EXIT_CODE);
n8thatsme 22 Light Poster

Yeah I know that its case sensitive. Is there anybody that can give me a code snippet for this? I'm trying to get this thing out of the way for my dad, I didn't think it would take me this long.

n8thatsme 22 Light Poster

I wrapped this in a do...while loop. I got it to exit when I type the EXIT_CODE. My problem now is when I search for say Bob Riley it will go into an infinite loop displaying the contents of the first object which is Fred Smith in my example. Now if I type Bob Jones it will go into an infinite loop displaying the contents of the first object, again it is Fred Smith, as well as displaying No Match. What is wrong with my logic? I need it to search the entire array of objects and compare it. Help would be GREATLY appreciated.

do
   {
       bool done = false;
       int  cntr    = 0;
       cout << "Enter first and last name (case sensative) of the employee"
	      << " you want to find: \n";
       cout << "Type " << EXIT_CODE << " to exit\n";
       getline(cin,info);

      while(cntr < MAX_EMPLOYEE_SIZE && !done)
	  {
	     full_name = EmployeeInfo[cntr].get_first_name() + " " 
			    + EmployeeInfo[cntr].get_last_name();
         if(info == full_name)
         {
            EmployeeInfo[cntr].display_info(); 
	    done = true;
         }
		 else
		 {
			 cout << "No Match";
		 }
         }
   }
   while(info != EXIT_CODE);
n8thatsme 22 Light Poster

This goes into an infinite loop, what am I doing wrong?

bool done = false;
      int  cntr    = 0;
      string full_name;
      while(cntr < MAX_EMPLOYEE_SIZE && !done)
	  {
	     full_name = EmployeeInfo[cntr].get_first_name() + " " 
			    + EmployeeInfo[cntr].get_last_name();
         if(info == full_name)
         {
            EmployeeInfo[cntr].display_info(); 
            done = true;
         }
         else
	    cout << "No Match";
n8thatsme 22 Light Poster

I still get an error for the &&. Here is the error:

Error 1 error C2676: binary '&&' : 'std::string' does not define this operator or a conversion to a type acceptable to the predefined operator c:\documents and settings\nate mcgee\my documents\visual studio 2005\projects\employee\employee\employee.cpp 80

n8thatsme 22 Light Poster

I had that working but it looped through 100 times of course, now I'm stumped. Anyone know what to do so it will stop looping after its found?

n8thatsme 22 Light Poster

This is what I'm kind of doing, of course I can't compare the first name and last name of the EmployeeInfo with &&. So if the user enters: Tom Jones it gets put into the info variable, I need to compare that with the get_first_name and get_last_name. Or some how split up the names in the info variable. I have to use an array in this even though I would use a vector. Assume that the array of objects is filled.

#define MAX_EMPLOYEE_SIZE 100

Employee EmployeeInfo[MAX_EMPLOYEE_SIZE];
string info;

cout << "Enter employee name to find: \n";
getline(cin,info);
      for(int cntr = 0; cntr < MAX_EMPLOYEE_SIZE; cntr++)
      {
         if(info == (EmployeeInfo[cntr].get_first_name() && 
			  EmployeeInfo[cntr].get_last_name()))
         {
            cout << EmployeeInfo.display_info(); // Display info here, what to pass to function?
         }
      }
n8thatsme 22 Light Poster

Ok, so I have an array of objects that have 3 get functions. Get last name, get first name (both strings) and get salary. What I'm trying to do is get a user to enter First name and Last name and it search the array for the persons first and last name. When it finds it I want it to display all of the info, the First name, last name and the salary. I was going to use a sequential search but I've never done it with objects using the get functions. Also, that function I want to display the contents what should I pass in? The object or something else?

Thanks,
n8thatsme

n8thatsme 22 Light Poster

Ok I still have the same output. I have 3 values per line in my file. Last name, first name and salary. I need it to read the last name and assign it into the object last name, read the first name and assign into the object first name and then read the salary as a float and assign to the object salary. The way I'm doing it now for the salary is reading it as a string and of course I can't do that because in my header it receives a float, not a string, but how can I fix this?

Updated code:

#include "stdafx.h"
#include "EmployeeHeader.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;

#define MAX_EMPLOYEE_SIZE 100

int main()
{
	ifstream indata;
	Employee EmployeeInfo[MAX_EMPLOYEE_SIZE];
	string info;
	int employee_count = 0;

   indata.open("employee.txt");
   if(!indata) 
   { 
      cout << "Error: file could not be opened" << endl;
      exit(1);
   }

   while ( indata>>info  && employee_count < MAX_EMPLOYEE_SIZE) 
   {
	  EmployeeInfo[employee_count].set_first_name(info);
	  cout << EmployeeInfo[employee_count].get_first_name();
	  cout << "\n";
	  EmployeeInfo[employee_count].set_last_name(info);
	  cout << EmployeeInfo[employee_count].get_last_name();
	  cout << "\n\n";
          EmployeeInfo[employee_count].set_salary(info);
	  cout << EmployeeInfo[employee_count].get_salary();
	  employee_count++;
   }
n8thatsme 22 Light Poster

Here is the updated code but the output isn't correct I don't think. First and last name are the same then it loops and first and last name are the same again. The updated code is as follows, the out put is posted after.

#include "stdafx.h"
#include "EmployeeHeader.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;

#define MAX_EMPLOYEE_SIZE 100

int main()
{
	ifstream indata;
	Employee EmployeeInfo[MAX_EMPLOYEE_SIZE];
	string info;
	int employee_count = 0;

   indata.open("employee.txt");
   if(!indata) 
   { 
      cout << "Error: file could not be opened" << endl;
      exit(1);
   }

   while ( !indata.eof()  && employee_count < MAX_EMPLOYEE_SIZE) 
   {
	  indata >> info;
	  EmployeeInfo[employee_count].set_first_name(info);
	  cout << EmployeeInfo[employee_count].get_first_name();
	  cout << "\n";
	  EmployeeInfo[employee_count].set_last_name(info);
	  cout << EmployeeInfo[employee_count].get_last_name();
	  cout << "\n\n";
	  employee_count++;
   }

And the output is like this. I put the "\n\n" to show whats happening.

Fred
Fred

Smith
Smith

40000
40000

McGee
McGee

Nate
Nate

63100.87
63100.87

63100.87
63100.87

End-of-file reached.
n8thatsme 22 Light Poster

Ok, my problem is that I'm reading from a file 3 values, a last name, first name and salary, for example: Key Bobby 43000
I have an array of objects for each person, so I neeed to read this file and assign the last name, first name, and salary to the appropriate variable. I've been out of C++ since April. I'm trying to do this for my Dad's business and I'm rusty. I have some debug statements in there to see if I'm actually inputing values. As of now I do not know what to pass to the set functions in my while loop because I don't want it to be to ineffecient. Any help is appreciated, I may be totally wrong with what I'm doing, let me know.

My header so far.

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class Employee
{
   string first_name, // Employee first name
          last_name;  // Employee last name
   float  salary;     // Monthly salary amount received
public:
   // Employee's constructors
          Employee();

   // Set member variables
   void   set_first_name(string employee_first_name);
   void   set_last_name (string employee_first_name);
   void   set_salary    (float monthly_salary);

   // Get member variables
   string get_first_name() {return first_name;}
   string get_last_name () {return last_name;}
   float  get_salary    () {return salary;}

   void print_employee_info();
};

Employee::Employee()
{
   first_name = '\0';
   last_name  = '\0';
   salary     = 0.0f;
}

void Employee::set_first_name(string employee_first_name)
{
	first_name = employee_first_name;
}

void Employee::set_last_name(string employee_last_name)
{
	last_name = employee_last_name;
}

void Employee::set_salary(float monthly_salary)
{
	if(monthly_salary > 0.0f)
		salary = monthly_salary;
	else
		salary = 0.0f;
}
Salem commented: Congratulations on using code tags on your first post, so few manage it. +22