Printing Structure inputs from class member function - c++

I would like to know how to input/initialize a start_date and end_date (which comes from a structure Date that has integers of month day and year from the function `initializeDate. Once I am able to initialize I assume I will be able to use the same logic in the printout member function.
struct Date
{
int month;
int day;
int year;
};
void initializeDate(Date &d)
{
cout<<"Please enter the month"<<endl;
cin>>start.month;
cout<<"Please enter the day"<<endl;
cin>>start.day;
cout<<"Please enter the year"<<endl;
cin>>start.year;
string dummy;
getline(cin, dummy);
}
edit: the error that I am getting is 'start' was not declared in this scope.

This is very basic, please read a good book on C++. Posting below because you have put in an effort :)
void Information::initializeDate(Date &d) //comes from the Information class.
{
// Commented as part of question change!
// Date d; // Guessing that the structure is the private member of the class.
cout<<"Please enter the month"<<endl;
cin>>d.month;
cout<<"Please enter the day"<<endl;
cin>>d.day;
cout<<"Please enter the year"<<endl;
cin>>d.year;
string dummy;
getline(cin, dummy);
}
** Just Edited the code as per your change in question

It looks like you keep updating the example code. Based on the current revision, I think this is what you want:
#include <iostream>
using namespace std;
struct Date
{
int month;
int day;
int year;
};
void initializeDate(Date &date)
{
cout<<"Please enter the month"<<endl;
cin>>date.month;
cout<<"Please enter the day"<<endl;
cin>>date.day;
cout<<"Please enter the year"<<endl;
cin>>date.year;
}
int main()
{
Date start, end;
initializeDate(start);
initializeDate(end);
cout << start.year << "/" << start.month << "/" << start.day << endl;
cout << end.year << "/" << end.month << "/" << end.day << endl;
return 0;
};

Ok, there are a couple of problems here, that you should target. First, to fix your code, the error is very simple: there isn't anywhere in your code in which a variable named start was declared/defined. So, the compiler is asking you what start is. You are trying, I assume, to initialize the values of the members of d, that you passed in the function initializeDate, and all you have to do is just replace every occurence of the word start with d, and you'll get:
void initializeDate(Date &d)
{
cout<<"Please enter the month"<<endl;
cin>> d.month;
cout<<"Please enter the day"<<endl;
cin>> d.day;
cout<<"Please enter the year"<<endl;
cin>> d.year;
string dummy;
getline(cin, dummy);
}
Now, although this works, it's not the best way to initialize the date. Since Date is a struct, you can initialize its members using a constructor method. This is achieved by writing it like this:
struct Date{
int day, month, year;
Date(int, int, int);
};
Date:: Date(int day, int month, int year){
this->day = day;
this->month = month;
this->year = year;
}
int main(){
Date today(11, 3, 2013);
cout << "today, the date is " << today.day << "-" << today.month << "-" << today.year << endl;
return 0;
}

Related

if else problem salary formula for loop desire loop user input

asking desire number to become the for loop(how many employee if input is 4 then 4 loop if 3 3 loops), salary formula not working, if else statement for string name to not accept number and vice versa integer to not accept letters. another one of my problem is how can I name the loop for example the question is name hours and rate then the cout should do 1. name hours rate, 2.name hours rate 3.name hours rate... the code is working.. just need some imporvements.
#include <iostream>
#include <cstdlib>
using namespace std;
void displayRules()
{
cout<<"====================="<<endl;
cout<<" EMPLOYEE-SALARY "<<endl;
cout<<"====================="<<endl;
cout<<" "<<endl;
}
int main()
{
char ans;
do
{
system("cls");
displayRules();
struct Employee
{
string name;
double hours;
double rate;
double salary;
Employee *next;
Employee *prev;
};
Employee *head;
head=NULL;
Employee *newEmployee;
Employee *EmpPointer;
Employee *nextEmpPointer;
Employee *prevEmpPointer;
string inpname;
int inpN;
double inphours;
double inprate;
double salary;
salary = (inprate*inphours);
for(int ctr=0; ctr<3; ctr++)
{
cout<<endl;
cout<<"Enter Name: \t\t";
cin>> inpname;
cout<<"Enter # Hours Worked: \t";
cin>> inphours;
if (inphours<0)
{
cout << "Invalid Input! Program Stopped. ";
return 0;
}
cout<<"Enter Rate per Hour: \t";
cin>> inprate;
if (inprate<0)
{
cout << "Invalid Input! Program Stopped. ";
return 0;
}
newEmployee = new Employee;
newEmployee->name=inpname;
newEmployee->hours=inphours;
newEmployee->rate=inprate;
newEmployee->next=NULL;
if (head==NULL)
head=newEmployee;
else
{
EmpPointer=head;
while (EmpPointer->next)
EmpPointer=EmpPointer->next;
EmpPointer->next=newEmployee;
}
}
cout<<endl;
Employee *displayPointer;
displayPointer=head;
system("cls");
cout<<"------------------------------------------------------------"<<endl;
cout<<" =Summary of PAYROLL= "<<endl;
cout<<"------------------------------------------------------------"<<endl;\
cout<<"Employee Name\t"<<"# Hours Worked\t"<<"Rate/Hour\t"<<"Salary\t"<<endl;
while (displayPointer)
{
cout<<displayPointer->name<<"\t\t";
cout<<displayPointer->hours<<"\t\t";
cout<<displayPointer->rate<<"\t\t";
cout<<displayPointer->salary<<endl;
displayPointer=displayPointer->next;
}
cout<<"------------------------------------------------------------"<<endl;
cout<<endl;
cout << "Would you like to run the program again? (Y/N) ";
cin>>ans;
}
while (ans == 'y' or ans == 'Y');
return 0;
}
Note: The salary wasn't being calculated so I fix that.
I broke your code into small functions in which each function only does one thing and one thing only (Single Responsibility Principle).
Also, I introduce function templates that allows you to reuse a function when you provide the type.
Finally, the code is missing a clean up of pointers to prevent memory leaks. Each time you use the keyword new to obtain a pointer to memory, you need later to check if the pointer contains null and if doesn't then use the keyword delete to free that memory, else you end with memory leaks in your code. Therefore, I leave you with the task to write the function that should iterate your employee list and free the memory to prevent memory leaks.
I hope this is useful.
#include <iostream>
#include <cstdlib>
using namespace std;
struct Employee {
string name;
double hours;
double rate;
double salary;
Employee *next;
Employee *prev;
};
void displayRules() {
cout<<"====================="<<endl;
cout<<" EMPLOYEE-SALARY "<<endl;
cout<<"====================="<<endl;
cout<<" "<<endl;
}
// Here we create a function template to make this code more reusable
template <typename T>
T consoleInput(const std::string& prompt) {
T value;
std::cout << prompt;
std::cin >> value;
return value;
}
// Lets create our own assert to exit the app.
void assertGreaterEqualThanZero(const double value, const std::string& prompt){
if (value < 0) {
cout << prompt;
exit(1);
}
}
// Small functions that do one thing only makes coding easy to debug
Employee* createEmployee(string name, int hours, int rate) {
Employee *newEmployee = new Employee;
newEmployee->name=name;
newEmployee->hours=hours;
newEmployee->rate=rate;
newEmployee->salary = (rate * hours);
newEmployee->next=NULL;
// You need to set and maintain ->prev
// if you are thinking on using a double linked list
// else remove it from the structure since is unused.
return newEmployee;
}
// This is a helper function to add new employees to a list
Employee* addToEmployeeList(Employee* list, Employee* newEmployee){
if (list==NULL) {
list = newEmployee;
} else {
Employee *EmpPointer = list;
while (EmpPointer->next)
EmpPointer=EmpPointer->next;
EmpPointer->next=newEmployee;
}
return list;
}
// The only purpose of this function is to print the list provided
void printEmployeList(Employee* employeeList){
Employee *currentEmployee = employeeList;
system("cls");
cout<<"------------------------------------------------------------"<<endl;
cout<<" =Summary of PAYROLL= "<<endl;
cout<<"------------------------------------------------------------"<<endl;
while (currentEmployee){
cout<<"Employee Name\t"<<"# Hours Worked\t"<<"Rate/Hour\t"<<"Salary\t"<<endl;
cout<<currentEmployee->name<<"\t\t";
cout<<currentEmployee->hours<<"\t\t";
cout<<currentEmployee->rate<<"\t\t";
cout<<currentEmployee->salary<<endl;
cout<<"------------------------------------------------------------"<<endl;
currentEmployee=currentEmployee->next;
}
}
// I leave you with this piece that is missing.
// TODO: create function that delete each employee in the list,
// then deletes the list in order to prevent memory leaks
int main() {
char ans;
do {
system("cls");
displayRules();
Employee *employeeList;
employeeList=NULL;
for(int ctr=0; ctr<3; ++ctr) {
// Lets declare and instantiate when we need it.
string name = consoleInput<string>("Enter Name: \t\t");
// No need to use inp (as inphours) in front of your variables
// It makes it harder to read. Just put hours as a name.
double hours = consoleInput<double>("Enter # Hours Worked: \t");
assertGreaterEqualThanZero(hours, "Invalid Input! Program Stopped.");
double rate = consoleInput<double>("Enter Rate per Hour: \t");
assertGreaterEqualThanZero(rate, "Invalid Input! Program Stopped. ");
Employee *newEmployee = createEmployee(name, hours, rate);
employeeList = addToEmployeeList(employeeList, newEmployee);
}
cout << endl;
printEmployeList(employeeList);
cout << "Would you like to run the program again? (Y/N) ";
cin>>ans;
} while (ans == 'y' or ans == 'Y');
return 0;
}

Program compiles but I think switch is ignored.

I am currently studying c++ but I fell behind a little bit, so I apologize if my question is obvious.
I have to create a program that asks for a student's name, GPA, Year of admission, and get a random 5 digit number generated for that person. The number of students will not exceed 42.
My program compiled (somehow) and I am able to get the error for invalid menu selection, however, whenever I give a valid selection (currently 1) nothing happens.
Maybe I am missing something, this is why I need help.
Here is my code.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
//print all the menu options
void print_menu()
{
cout<<"\nRCNJ Registrar Menu:"<<"\n"
<<"\n"
<<"[1] Add a student"<<"\n"
<<"[2] Display all students"<<"\n"
<<"[3] Display by year"<<"\n"
<<"[4] Display statistics"<<"\n"
<<"[5] Quit"<<"\n";
}
//get and return the student's name
void get_name(string& student_name) //call student_name after that.
{
cout<<"Please enter the sudent's name: ";
cin >> student_name;
cout<<"\n";
}
//validate and return gpa
double get_gpa()
{
double student_gpa = 0;
cout<<"Please enter the GPA: ";
cin >>student_gpa;
cout<<"\n";
while (student_gpa > 4 || student_gpa < 0)
{
cout<<"Please enter a valid GPA for the student (0.00 - 4.00): ";
cin >> student_gpa;
cout<<"\n";
}
return student_gpa;
}
//validateand return year
int get_year()
{
int student_year = 0;
cout<<"Please enter the year: ";
cin >> student_year;
cout<<"\n";
while (student_year >2016 || student_year <1972)
{
cout<<"Please enter a valid year (min 1972, max 2016): ";
cin >> student_year;
cout<<"\n";
}
return student_year;
}
//generate the student's R#
int generate_number()
{
int r_number;
srand (time(NULL));
r_number = rand() % 89999 + 10000;
return r_number;
}
//save info. Include get_name, get_gpa, get_year
void input_new_student()
{
string student_name;
double student_gpa;
int student_year;
int r_number;
int s_name, s_gpa, s_year, r_num;
get_name(student_name);
get_gpa();
get_year();
generate_number();
}
//display all students in the proper format
void print_all()
{
}
//get a year as selection and print all students that are the same year
void print_by_year()
{
}
//display statistics based on entered students
void print_statistics()
{
}
//validate and return the menu option selected by the user.
//it should call print_menu defined earlier
int get_selection(int menu_choice)
{
menu_choice = 0;
cout<<"\n"
<<"Selection: ";
cin >> menu_choice;
cout<<"\n";
while (menu_choice > 5 || menu_choice< 1)
{
cout<<" Menu choice is invalid. Please re-enter (1 - 5): ";
cin>> menu_choice;
cout<<"\n";
}
return menu_choice;
}
int main()
{
string student_name;
double student_gpa;
int student_year;
int r_number;
int menu_choice;
int s_name=0;
int s_gpa=0;
int s_year=0;
int r_num=0;
string nameArray[42];
s_name++;
double gpaArray[42];
s_gpa++;
int yearArray[42];
s_year++;
int ramapoArray[42];
r_num++;
print_menu();
get_selection(menu_choice);
switch (menu_choice)
{
case 1:
input_new_student();
nameArray[s_name] = student_name;
gpaArray[s_gpa] = student_gpa;
yearArray[s_year] = student_year;
ramapoArray[r_num] = r_number;
break;
}
return 0;
}
I dont have permission to comment, hence adding it here.
In you main(),
get_selection(menu_choice);
switch (menu_choice)
You return menu_choice, but there is none to take the value, you end you using garbage value as it is uninitialized.
So two ways you can do it, either by passing the address/reference of menu_choice or by return value. try either of these it should work, though I have not gone through the rest of your program.
As suggested by others, try a debugger e.g. gdb?

How do I call a function from another .cpp file into the file where my int main() is? [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 7 years ago.
So my program requires me to make a function in one file, and call it into another.
I have one file called convertdays.cpp like this:
#include <iostream>
int convertdays(int, int, int);
int convertdays(int month, int day, int year)
{
int date;
date = year * 1000 + month * 100 + day;
return date;
}
Then I have another file where my int main() stuff is, like this:
#include <iostream>
using namespace std;
int main()
{
int day, month, year;
cout << "Please enter the month: " << endl;
cin >> month;
cout << "Please enter the day: " << endl;
cin >> day;
cout << "Please enter a year: " << endl;
cin >> year;
convertdays(month, day, year); //convertdays stays in red though.
//Still need to add a couple of more things but not necessary right now.
system("Pause");
return 0;
}
How do I make this work where I can keep all of my functions in another file and call them in when I need them?
Make a file called "convertdays.h", containing the function declaration:
int convertdays(int, int, int);
This is called a header file.
Then at the top of main.cpp:
#include "convertdays.h"
(It's a good idea to put the same thing at the top of convertdays.cpp, though not strictly necessary.)
Then when you build the executable, link main.o and convertdays.o.

Trouble calculating cumulative sum of products

I have to make a program that calculates the population of the country each year .
in 2014 the populatin is x and in 2015 is x*(12%) and each year is incremented by 12%.
I've tryed to do this way but couldn't get through it:
#include<iostream>
using namespace std;
int main(){
int year;
double pop=344000
cout<<"Year of population: ";
cin >> year;
switch(year){
case 2014: cout<< "344000\n";
break;
case 2015: cout<< pop+=* 0.12 + pop ; //last year pop *0.12+ last year pop
break;
cout <<year;
}
system("pause");
return year;
}
I know its a mess but i really I'm noob in c++
increment next year`s population by 12 percent of last one , we check how many years is passed and increase the population with that no need for switch
int main(){
int year;
int baseYear=2014;
int dif;
int population=2000; //number of people in 2014
cout<<"Year of population: ";
cin >> year;
dif=year-baseYear
for(int i=0;i<dif;i++)
population+= ((0.12)*population)
cout << population;
}
I hope looking at this code will help you to understand what you are missing.
include<iostream.h>
void main()
{
int population= 3000000;
int year;
cout<<"Enter a year greater than or equal to 2014 ";
cin>>year;
if(year<2014)
cout<<"year must be greater than or equal to 2014";
elseif(year==2014)
cout<<population;
else
{
int i=2014;
while(i<=year)
{
population=population*1.12;
i++;
}
cout<<"population";
}
}

How to extract the details of the highest paid employee in files?

I am having problem in extracting the highest paid employee from empdetails.txt and finally displaying it to the user. i have completed getting the details from the user and merging the two files but for displaying highest paid using functions, i have no idea about it.
here is my code till now:
#include<iostream>
#include<conio.h>
#include<fstream>
using namespace std;
class emp
{
int num,age;
char name[20],dep[5];
public:
void getdata()
{
cout<<"\n\n Name = ";
cin>>name;
cout<<"\n Emp Num = ";
cin>>num;
cout<<"\n Department= ";
cin>>dep;
cout<<"\n Age = ";
cin>>age;
}
void display1()
{
cout<<"\n"<<name<<"\t"<<num<<"\t"<<dep<<"\t\t"<<age;
}
};
class sal
{
float gs,ns;
public:
void getsal()
{
cout<<"\n Gross sal = ";
cin>>gs;
cout<<"\n Net sal = ";
cin>>ns;
}
void display2()
{
cout<<"\t"<<gs<<"\t"<<ns;
}
};
void display()
{
emp e;sal s;
ifstream fil1;
fil1.open("empdetails.txt",ios::in);
cout<<"\n\n Name \t Emp Num \t Dep \t Age \t Gross Sal \t Net Sal \n";
while(!fil1.eof())
{
fil1.read((char*)&e,sizeof(e));
e.display1();
fil1.read((char*)&s,sizeof(s));
s.display2();
}
}
int main()
{
int n;
emp e1;sal s1;
ofstream fil1,fil2,fil3;
fil1.open("emp.txt",ios::out);
fil2.open("sal.txt",ios::out);
fil3.open("empdetails.txt",ios::out);
cout<<"\n How many employee details do you want to enter = ";
cin>>n;
cout<<"\n Enter the deatils one by one \n";
for(int i=0;i<n;i++)
{
e1.getdata();
fil1.write((char*)&e1,sizeof(e1));
s1.getsal();
fil2.write((char*)&s1,sizeof(s1));
fil3.write((char*)&e1,sizeof(e1));
fil3.write((char*)&s1,sizeof(s1));
}
fil1.close();
fil2.close();
fil3.close();
cout<<"\n\n\t\t Merged file contents \n\n\t\t";
display();
getch();
return 0;
}
how can i make a function and what conditions to use?
You don't need a function, there's already one: std::max_element. It can figure out that you're working on class emp (the first two arguments to std::max_element. It can't figure out that you want employees sorted by salary, so that is the third argument that you have to provide: a function that takes two employees and which returns true if the first employee earns less than the second. (Sounds weird, but this allows you to use the same function for std::min_element)