Been trying to figure out how to input information into an array and output it from structured variables. I can input and output the information easy without using arrays, however I am trying have a list of workers inputed from the keyboard. I also need to calculate the wage earned for each worker, but If I can just figure out the format of the simple information from the first three variables I can figure that part out on my own. I have tried to call the input function in the array but have had no success so I just deleted it and left the functions.
#include<iostream>
using namespace std;
struct Worker
{
int idNumber;
int hoursWorked;
double hourlyRate;
double earned;
};
void input(Worker & theData);
//Postcondition: theData.idNumber, theData.hoursWorked, and theData.hourlyRate are given input values
// the user must input into these values.
void print(const Worker &);
void input(Worker[], int howMany);
void print(const Worker[], int);
void main()
{
Worker arr[10];
Worker Data;
input(Data);
print(Data);
input(arr[10],7);
system("pause");
}
void input(Worker& theData) {
cout << "Enter the Employee idNumber ";
cin >> theData.idNumber;
cout << "Enter the Hours Worked. ";
cin >> theData.hoursWorked;
cout << "Enter the HoutlyRate for under 41 hours. ";
cin >> theData.hourlyRate;
}
void input(Worker arr[], int howMany)
{
for (int i = 0; i < howMany; i++)
{
input(arr[i]);
}
}
void print(const Worker& w) {
cout << w.idNumber << "\n" << w.hoursWorked << "\n" << w.hourlyRate << "\n" << w.earned << endl;
}
void print(const Worker arr[], int howMany)
{
for (int i = 0; i < howMany; i++)
{
print(arr[i]);
}
}
You're almost there. This sounds like coursework, so I'm not going to suggest using a std::vector. Look up std::vector, by the way, and use it when you can. It'll save you a lot of grief.
To use an array, you first need to know the size of the array and reserve space. There are a number of ways to get the number of workers, but this is probably the simplest:
int main()
{
int howMany;
cout << "How many?";
cin >> howMany;
Worker * workers = new Worker[howMany];
After that, it's pretty much keep doing what you're doing, but call the array-based functions and clean up when you're done.
input(workers, howMany);
calc(workers, howMany);
print(workers, howMany);
system("pause");
delete[] workers;
}
Ok so if I am understanding you correctly, you would like to be able to read in information about a bunch of workers and store it into an array of structs. Correct my if I am wrong, but if that is what you would like to do I think you can actually cheat this a little bit using the single worker input function like so.
struct Worker
{
int idNumber;
int hoursWorked;
double hourlyRate;
double earned;
};
void input(Worker& theData) {
cout << "Enter the Employee idNumber ";
cin >> theData.idNumber;
cout << "Enter the Hours Worked. ";
cin >> theData.hoursWorked;
cout << "Enter the HoutlyRate for under 41 hours. ";
cin >> theData.hourlyRate;
}
void input(Worker arr[], int howMany)
{
for (int i = 0; i < howMany; i++)
{
input(arr[i]);
}
}
void print(const Worker& w) {
cout << w.idNumber << "\n" << w.hoursWorked << "\n" << w.hourlyRate << "\n" << w.earned << endl;
}
void print(const Worker arr[], int howMany)
{
for (int i = 0; i < howMany; i++)
{
print(arr[i]);
}
}
Some notes, you want to delete the const from the array input function. You are going to modify the array it can't be const. I added some spaces after the "Enter the blah. " so that it looks prettier. You can figure out the calc on your own as you said, just follow the form here to figure out how to do that for an array of things. Once you have written to the function for a single guy, it is pretty simple to do it for the array as you can see.
Also for your education just remember that arrays are inherently pass by reference so that's why we can just throw them into the pass by reference functions with no problems.
I should add that in the future you can access the parts of each workers information from the array directly by using:
arr[i].idNumber;
arr[i].any_struct_variable;
Thank you all for helping! I finally figured it out and It is working well.
#include<iostream>
using namespace std;
struct Worker
{
int idNumber;
int hoursWorked;
double hourlyRate;
double earned;
};
void input(Worker & theData);
//Postcondition: theData.idNumber, theData.hoursWorked, and theData.hourlyRate are given input values
// the user must input into these values.
void print(const Worker &);
void calcInput(Worker[], int howMany);
void input(Worker[], int howMany);
void print(const Worker[], int);
void calc(Worker & theWage);
void main()
{
Worker Data;
int howMany;
cout << "How many?";
cin >> howMany;
Worker * workers = new Worker[howMany];
input(workers, howMany);
calcInput(workers, howMany);
print(workers, howMany);
system("pause");
delete[] workers;
}
void input(Worker& theData) {
cout << "Enter the Employee idNumber ";
cin >> theData.idNumber;
cout << "Enter the Hours Worked. ";
cin >> theData.hoursWorked;
cout << "Enter the HoutlyRate for under 41 hours. ";
cin >> theData.hourlyRate;
}
void input(Worker arr[], int howMany)
{
for (int i = 0; i < howMany; i++)
{
input(arr[i]);
}
}
void print(const Worker& w) {
cout << w.idNumber << "\n" << w.hoursWorked << "\n" << w.hourlyRate << "\n" << w.earned << endl;
}
void print(const Worker arr[], int howMany)
{
for (int i = 0; i < howMany; i++)
{
print(arr[i]);
}
}
void calc(Worker & theWage)
{
if (theWage.hoursWorked <= 40)
{
theWage.earned = theWage.hoursWorked * theWage.hourlyRate;
}
else
{
int basePay;
basePay = theWage.hoursWorked * theWage.hourlyRate;
theWage.earned = (theWage.hoursWorked - 40) * 1.5 + basePay;
}
}
void calcInput(Worker arr[], int howMany)
{
for (int i = 0; i < howMany; i++)
{
calc(arr[i]);
}
}
Related
I know this may be something obvious to some with experience but I am in the middle of my first real class for C++ programming. I have come across something in my code that I have been trying to resolve without any success. I am trying to extract the sum of the total value of "m_cost" stored within a array that is inside of these class modules. I want to output the total value inside of a switch statement for print out. Just seeing if someone can point me in the right direction or if I have completely gone off-track with the logic.
Project Code section in question:
void materialsMenu()
{
Inventory record[MAX_REC];
int i, n;
cout << "\n=====Inventory Management=====\n";
cout << "\nHow many Materials are there to be used? : ";
cin >> n;
cout << "Enter " << n << " Materials\n";
for (i = 0; i < n; i++)
record[i].getdata();
cout << "\n\n---Material Information---\n";
cout << "\n" << setw(8) << "Item Name "
<< setw(10) << " Price per foot "
<< setw(19) << " Cost " << endl;
cout << endl << "-------------------------------------------" << endl;
for (i = 0; i < n; i++)
record[i].showdata();
}
void Inventory::getdata() {
cout << endl;
cout << "\nEnter Material Name : ";
cin >> itemName;
cout << "Enter Price Per Foot : ";
cin >> ppf;
cout << "Enter Total Length Needed in Feet (ft) : ";
cin >> length;
cout << endl;
m_cost = ppf*length;
m_costT=???????? **this is the issue**
}
Materials.H file contents:
#ifndef MATERIALS_H
using namespace std;
class Materials {
private:
char itemName[15];
float ppf;
float length;
double m_cost;
float m_costT;
public:
Materials()
{
ppf = 0;
length = 0;
m_cost = 0;
m_costT = 0;
}
Materials(int itemName, float ppf, float length, double m_cost, float
m_costT)
{
length = getLength();
ppf = getPpf();
m_cost = getCost();
m_costT = getTotal();
}
float getLength()
{
return length;
}
float getPpf()
{
return ppf;
}
double getCost()
{
return m_cost;
}
float getTotal()
{
return m_costT;
}
void getdata();
void showdata();
};
#endif // !MATERIALS_H
Consider something like this to hold your records. It's very simple, but it demonstrates the idea of one class holding another and shows information hiding and all sorts of other tidbits. You are struggling to get that total because the Record class shouldn't care about this. The total is a concept outside of the scope of a Record. And as such, it is very difficult to calculate this from where you wanted to do it. (Though it is possible, it breaks all sorts of C++ rules and should be avoided)
Example:
class Record;
class RecordHolder
{
public:
int GetTotal()
{
int retVal = 0;
for(int i=0; i<10; i++) // Magic number 10 for demo purposes only...
{
retVal += records[i].m_cost; // Or use a public get function.
}
return retVal;
}
private:
Record records[10]; // Magic number 10 for demo purposes only...
};
The RecordHolder could also do printing, add/removing records, etc. It controls the records array. The Records are just Records and don't care about such management.
I don't understand why getAges is being skipped.
#include <iostream>
#include <cctype>
using namespace std;
int getAges(int age, const int SIZE);
char getChoice();
void displayInOrder(int numbers[], const int SIZE, char choice);
void displayInReverse(int numbers[], const int SIZE, char choice);
int main()
{
const int SIZE = 5;
int numbers[SIZE] = { 1, 2 ,3 ,4, 5 };
char answer;
int age;
char choice;
if (toupper(choice) == 'O')
{
displayInOrder(numbers, SIZE, choice);
}
else if (toupper(choice) == 'R')
{
displayInReverse(numbers, SIZE, choice);
}
else
{
cout << "Invalid entry! - Must be O or R\n\n";
}
if (toupper(answer) == 'Y')
{
system("cls");
age = getAges(age, SIZE);
choice = getChoice();
displayInOrder(numbers, SIZE, choice);
displayInReverse(numbers, SIZE, choice);
cout << "Run program again (Y or N)? ";
cin >> answer;
break;
}
else if (toupper(answer) == 'N')
{
return 0;
}
return 0;
}
int getAges(int age, const int SIZE)
{
cout << "Enter " << SIZE << " ages: \n\n";
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
return age;
}
char getChoice()
{
char choice;
cout << "How do you want to see the ages displayed? \n\n Enter O for In Order, or R for In Reverse.\n\n";
cin >> choice;
return choice;
}
void displayInOrder(int numbers[], const int SIZE, char answer)
{
cout << "Here are the ages in order: \n\n";
for (int i = 0; i < SIZE; i++)
{
cout << numbers[i] << endl;
}
}
void displayInReverse(int numbers[], const int SIZE, char answer)
{
cout << "Here are the ages in reverse order: \n\n";
for (int i = SIZE - 1; i >= 0; i--)
{
cout << numbers[i] << endl;
}
}
I started working on this before the OP updated the title to their original question about "while loops & break statements". However at the time I came across this question the OP had originally removed the while loops. I was looking over the provided functions to get an idea of what the OP was trying to do and this is what I have come up with.
First: while loops are exactly what you want here, but you want a specific type of while loop, a do-while loop in this case.
Next: There is no need for break statements if you know how to structure your do-while loop correctly.
Finally: I made some modifications to the OP's existing functions by changing or removing unnecessary parameter(s), return type(s) & code duplication. I removed a function that was no longer needed. I changed the output formatting of the messages to display a clean looking program. I also removed a bad practice of having using namespace std; in the global scope.
I did this to demonstrate to the OP how a while loop can be constructed without the need of break statements and that they were originally on the right track but needed a little bit of assistance to get on their way.
Here is the source code to a working program on what I think the OP was aiming to do.
#include <iostream>
#include <cctype>
void getAge( int& age );
void displayInOrder( int numbers[], const int SIZE);
void displayInReverse( int numbers[], const int SIZE );
int main() {
const int SIZE = 5;
int numbers[SIZE] = { 0 };
char answer = '\0';
int age = 0;
char choice = '\0';
std::cout << "========================================================================\n"
<< "This program will have the user enter in "
<< SIZE
<< " Ages. \nThen ask the user in which order to display the list of ages.\n"
<< "Finally the program will ask the user if they want to continue or not.\n"
<< "========================================================================\n\n";
do {
for ( int i = 0; i < SIZE; i++ ) {
getAge( age );
numbers[i] = age;
}
std::cout << "\nPlease enter 'O' for ordered or 'R' for reversed list.\n";
std::cin >> choice;
if ( toupper( choice ) == 'O' ) {
displayInOrder( numbers, SIZE );
}
if ( toupper( choice ) == 'R' ) {
displayInReverse( numbers, SIZE );
}
std::cout << "\nDo you want to run program again (Y/N)?";
std::cin >> answer;
} while ( toupper( answer ) == 'Y' );
return 0;
}
void getAge( int& age ) {
int temp;
std::cout << "Enter an age: \n";
std::cin >> temp;
age = temp;
}
void displayInOrder( int numbers[], const int SIZE ) {
std::cout << "\nHere are the ages in order: \n";
for ( int i = 0; i < SIZE; i++ ) {
std::cout << numbers[i] << std::endl;
}
}
void displayInReverse( int numbers[], const int SIZE ) {
std::cout << "\nHere are the ages in reverse order: \n";
for ( int i = SIZE - 1; i >= 0; i-- ) {
std::cout << numbers[i] << std::endl;
}
}
Recently in my c++ class we have learned about pointers and classes.
I'm trying to make a program that has a class Student, which we will point to give each student a name and test score.
After entering both name and test score, they are sorted and then listed in order of highest to lowest.
I believe all my syntax to be correct, however I am still learning. The problem I am having is that the first time I use my class I get an uninitialized local variable error, any help on how to fix this?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <array>
using namespace std;
class Student {
private:
double score;
string name;
public:
void setScore(double a) {
score = a;
}
double getScore() {
return score;
}
void setName(string b) {
name = b;
}
string getName() {
return name;
}
};
void sorting(Student*, int);
int main()
{
Student *students;
string name;
int score;
int *count;
count = new int;
cout << "How many students? ";
cin >> *count;
while (*count <= 0) {
cout << "ERROR: The number of students must be greater than 0.\n";
cin >> *count;
}
for (int i = 0; i < *count; i++) {
cout << "Please enter the students name: ";
cin >> name;
students[i].setName(name);
cout << "Please enter " << students[i].getName() << "'s score: ";
cin >> score;
while (score < 0) {
cout << "ERROR: Score must be a positive number.\n";
cin >> score;
}
students[i].setScore(score);
}
sorting(students, *count);
for (int i = 0; i < *count; i++) {
cout << students[i].getName() << ": " << students[i].getScore() << endl;
}
system("PAUSE");
return 0;
}
void sorting(Student *s, int size) {
for (int i = 0; i < size; i++) {
for (int j = i; j < size; j++) {
if (s[j].getScore() > s[(j + 1)].getScore()) {
int tmp = s[(j + 1)].getScore();
s[(j + 1)].setScore(s[j].getScore());
s[j].setScore(tmp);
string tmp1 = s[(j + 1)].getName();
s[(j + 1)].setName(s[j].getName());
s[j].setName(tmp1);
}
}
}
}
First off, your Student class can be simplified to this:
struct Student {
double score;
std::string name;
};
Because the accessors do absolutely nothing. I've also added the std:: prefix because using namespace std is considered a bad practice.
Now, instead of using the pointer to store the students, include vector and use that:
std::cout << "How many students? ";
int count;
std::cin >> count;
std::vector<Student> students(count);
The loading routine can also be simplified given the absence of accesors:
for (auto& student : students) {
std::cout << "Please enter the students name: ";
std::cin >> student.name;
std::cout << "Please enter " << student.name << "'s score: ";
std::cin >> student.score;
while (score < 0) {
std::cout << "ERROR: Score must be a positive number.\n";
std::cin >> student.score;
}
}
And actually once you have that, you could just put it in istream& operator>>(istream&, Student&) and reduce it to:
std::copy_n(std::istream_iterator<Student>(std::cin), students.size(), students.begin());
No need now for temporary variables anymore (and even if you want to use them, they should be defined just before the use, so inside of the loop).
The last thing is your sorting routine. First off, there's std::sort that you can use instead if you simply provide a comparator:
std::sort(
begin(students),
end(students),
[](Student const& a, Student const& b) { return b.score < a.score; }
);
If you insist on writing the sorting routine yourself, at least use std::swap.
I am trying to figure out what is wrong with my code. I must use a structure to prompt the user for a workers idNumber, hoursWorked, and hourlyWage. I have the idNumber, hoursWorked, and hourlyWage working well, however the problem lies in my calc function. I cannot figure out how to calculate the money earned with overtime being 1.5 times and to be able to print that to the screen. I keep getting a mash up of weird numbers.
#include<iostream>
using namespace std;
struct Worker
{
int idNumber;
int hoursWorked;
double hourlyRate;
double earned;
};
void input(Worker & theData);
//Postcondition: theData.idNumber, theData.hoursWorked, and theData.hourlyRate are given input values
// the user must input into these values.
void print(const Worker &);
void calc(Worker & theWage);
void main()
{
Worker Data;
input(Data);
print(Data);
system("pause");
}
void input(Worker & theData)
{
cout << "Enter the Employee idNumber";
cin >> theData.idNumber;
cout << "Enter the Hours Worked.";
cin >> theData.hoursWorked;
cout << "Enter the HoutlyRate for under 41 hours.";
cin >> theData.hourlyRate;
}
void print(const Worker & w)
{
cout << w.idNumber << "\n"
<< w.hoursWorked << "\n"
<< w.hourlyRate << "\n"
<< w.earned << endl;
}
void calc(Worker & theWage)
{
if (theWage.hoursWorked <= 40)
{
theWage.earned = theWage.hoursWorked * theWage.hourlyRate;
}
else
{
int basePay;
basePay = theWage.hoursWorked * theWage.hourlyRate;
theWage.earned = (theWage.hoursWorked - 40) * 1.5 + basePay;
}
}
Your calc() function must be called in main before your print() function.
void main()
{
Worker Data;
input(Data);
calc(Data); // This line was forgotten.
print(Data);
system("pause");
}
The weird number you saw was the uninitialized earned variable.
// header.h
#include <iostream>
#include <list>
#include <fstream>
using namespace std;
class Biblioteca
{
public:
Biblioteca();
void closeFile();
bool chose();
ofstream Intrare;
ofstream Memorare;
};
class Publicatii:public virtual Biblioteca
{
public:
string retTitlu();
string retEditura();
string retAutor();
int retAn();
int retTiraj();
int retNumar();
int retFrecventa_de_aparitii();
protected:
string Titlu, Editura, Autor;
int An, Tiraj, Numar, Frecventa_de_aparitii;
};
class Carti: public Publicatii , public virtual Biblioteca
{
public:
void readBook();
Carti();
void insertMyBook();
void writeBookFile();
void inTitlu(Carti& a);
void inEditura(Carti& a);
void inAutor(Carti& a);
void inTiraj(Carti& a);
void inAn(Carti& a);
protected:
list<Carti*>books;
list<Carti*>::iterator i;
};
class Reviste: public Publicatii , public virtual Biblioteca
{
public:
void readMagazine();
Reviste();
void insertMyMagazine();
void writeMagazineFile();
protected:
list<Reviste*> magazine;
list<Reviste*>::iterator j;
};
The other cpp file of the header
#include<iostream>
#include<string>
#include"biblioteca.h"
#include <list>
#include<fstream>
//-----Biblioteca------
Biblioteca::Biblioteca()
{
Memorare.open("in.txt");
}
void Biblioteca::closeFile()
{
Memorare.close();
}
bool Biblioteca::chose()
{
int k;
cout << "Ce doriti sa introduceti?" << endl << endl;
cout << "1--Carte" << endl;
cout << "2--Biblioteca" << endl;
cin >> k;
switch (k)
{
case 1:
return true;
break;
case 2:
return false;
break;
}
}
//-------Publicatii------
string Publicatii::retTitlu()
{
return Titlu;
}
string Publicatii::retEditura()
{
return Editura;
}
string Publicatii::retAutor()
{
return Autor;
}
int Publicatii::retAn()
{
return An;
}
int Publicatii::retTiraj()
{
return Tiraj;
}
int Publicatii::retNumar()
{
return Numar;
}
int Publicatii::retFrecventa_de_aparitii()
{
return Frecventa_de_aparitii;
}
//---------Carti---------
void Carti::inTitlu(Carti& a)
{
Titlu = a.retTitlu();
}
void Carti::inEditura(Carti& a)
{
Editura = a.retEditura();
}
void Carti::inAutor(Carti& a)
{
Autor = a.retAutor();
}
void Carti::inTiraj(Carti& a)
{
Tiraj = a.retTiraj();
}
void Carti::inAn(Carti& a)
{
An = a.retAn();
}
void Carti::readBook()
{
cout << "\nO noua carte" << endl<<endl;
cout << "\nTitlu= ";
cin >> Titlu;
cout << "\nEditura= ";
cin >> Editura;
cout << "\nAn= ";
cin >> An;
cout << "\nTiraj= ";
cin >> Tiraj;
cout << "\nAutor= ";
cin >> Autor;
}
Carti::Carti()
{
books.resize(1);//one book
}
void Carti::insertMyBook()
{
Carti carti;
for (i = books.begin(); i != books.end(); i++)
{
carti.readBook();
(*i)->inTitlu(carti);
(*i)->inEditura(carti);
(*i)->inAn(carti);
(*i)->inTiraj(carti);
(*i)->inAutor(carti);
//books.insert(i, *i);
}
}
void Carti::writeBookFile()
{
Memorare << "---Carti---" << endl;
for (i = books.begin(); i != books.end(); i++)
Memorare << *i << " ";
}
//-------Reviste--------
void Reviste::readMagazine()
{
cout << "\nO noua revista" << endl<< endl;
cout << "\nTitlu= ";
cin >> Titlu;
cout << "\nEditura= ";
cin >> Editura;
cout << "\nAn= ";
cin >> An;
cout << "\nTiraj= ";
cin >> Tiraj;
cout << "\nNumar= ";
cin >> Numar;
cout << "\nFrecventa de aparitie= ";
cin >> Frecventa_de_aparitii;
}
Reviste::Reviste()
{
magazine.resize(1);//one magazine
}
void Reviste::insertMyMagazine()
{
Reviste reviste;
for (j = magazine.begin(); j != magazine.end(); j++)
{
reviste.readMagazine();
//some conde
magazine.insert(j, *j);
}
}
void Reviste::writeMagazineFile()
{
Memorare << "---Reviste---" << endl;
for (j = magazine.begin(); j != magazine.end(); j++)
cout << *j << " ";
}
Sorry for the code thone here, I'm new to Stackoverflow and I'm in a hurry, that's why I don't write "beautiful code". My problem is, when I want to just insert elements in my list
void Carti::insertMyBook()
{
Carti carti;
for (i = books.begin(); i != books.end(); i++)
{
carti.readBook();
(*i)->inTitlu(carti);
(*i)->inEditura(carti);
(*i)->inAn(carti);
(*i)->inTiraj(carti);
(*i)->inAutor(carti);
books.insert(i, *i);
}
}
it's working like a clockwork and after I compile I type some information from my keyboard and at the end I get a big error like "Acces Violation Reading 00000001C"
Why? I tried other metods like allocating dynamic memory with the new operator, I tried a lot of things but in the end I have like this error or type "example" doesn't match with "example".
Sorry for my bad English spelling, but in this program I just wanted to make a program that reads magazines and boooks and stored to a library named "biblioteca", and "carte" means books and " Reviste" means magazine... and I want it to be memorized in a list because I need to insert elements or delete what ever book or magazine I choose...and all the information I want to be saved in a file for instance "out.txt" or "in.txt"
The crash is because the iterator is NULL at line (*i)->inTitlu(carti);.
The issue is in method:
Carti::Carti()
{
books.resize(1);//one book
}
and books are:
list<Carti*>books;
What you are trying to is to resize the list of Carti's to 1 but as you have a list of pointers to Carti objects rather than Carti objects, resizing operation will not create a Carti object by calling it's constructor but a pointer.
Apart from that you have major issues with your design and coding, a Carti object storing a list of other pointers-to-Carti objects definitely is not a good idea. You may consider creating another 'holding' class to store a list of Carti's you have created.