Filling struct with void function - c++

I was trying to fill and show the data of a struct using void functions, the problem is that it looks that there is a problem once I try to fill the struct "persona" with the void function "llenar", it does not fill it, once I show the data (with "mostrar") in the console it looks like it is empty, this problem does not appear when I do not use the void function "llenar".
#include <iostream>
using namespace std;
struct persona
{
string nombre; //elementos
float fisica;
float quimica;
float matematica;
float ponderado;
};
void llenar (persona P)
{
cout<<"nombre: ";
cin>>P.nombre;
cout<<" nota fisica: ";
cin>>P.fisica;
cout<<" nota quimica: ";
cin>>P.quimica;
cout<<" nota matematica: ";
cin>>P.matematica;
}
void mostrar(persona P)
{
cout<<"nombre: ";
cout<<P.nombre<<endl;
cout<<" nota fisica: ";
cout<<P.fisica<<endl;
cout<<" nota quimica: ";
cout<<P.quimica<<endl;
cout<<" nota matematica: ";
cout<<P.matematica<<endl;
}
int main()
{
int C;
//float Po;
cout<<"Enter the number of people: ";
cin >> C;
persona * P1;
P1 = new persona [C];
for(int i = 0 ; i<C ; i++)
{
cout<<"Person "<<i+1<<" :"<<endl;
llenar(P1[i]);
// NOT USING void "llenar"
/*
cout<<"Igresa nombre: ";
cin>>P1[i].nombre;
cout<<"Igresa nota fisica: ";
cin>>P1[i].fisica;
cout<<"Igresa nota quimica: ";
cin>>P1[i].quimica;
cout<<"Igresa nota matematica: ";
cin>>P1[i].matematica;
*/
mostrar(P1[i]);
}
return 0;
}
To make a long story short, does someone knows how to fill a struct like "persona" from a void function?

You have to pass the argument by reference, so that it can be modified:
void llenar (persona P); // becomes ==>
void llenar (persona &P);

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;
}

Function with structure as argument producing error: free(): invalid pointer: 0x00007efd47b

I've made an addDepartment function that takes a structure as an argument. When I enter input to initialize the "dept[counter].departmentHead" at the bottom of the function, it triggers the error message.
I'm copying the logic from another code I wrote using classes instead of structures and that one works fine so I'm really not sure why this one isn't working. Tried messing with the index to make sure I wasn't going over the size of the array but that doesn't seem to fix the issue.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
using namespace std;
struct Department{
string departmentName;
string departmentHead;
int departmentID;
double departmentSalary;
};
//...
Department addDepartment(Department dept[3]){
int repeat=0;
int counter=0;
if (counter>2){
cout<<"The array is full, you can not add any more Departments."<<endl;
}
else{
cout << "Please Enter Department Details:"<<endl;
cout << "Department ID : ";
cin >> dept[counter].departmentID;
for(int x=0; x<3; x++){
for (int y=x+1; y<3; y++){
if(dept[x].departmentID==dept[y].departmentID)
repeat++;
}
}
if(repeat!=0)
cout<<"Value must be unique!"<<endl;
else{
cout << "Department Name : ";
cin >> dept[counter].departmentName;
cout << "Head of Department : ";
cin >> dept[counter].departmentHead;
counter++;
}
}
}
//...
int main()
{
Employee emp[5];
Department dept[3];
initialID(emp,dept,0);
initialID(emp,dept,1);
int response;
while(response!=6){
displayMenu();
cout<< "Please make a selection : \n";
cin >> response;
while((response!=1)&&(response!=2)&&(response!=3)&&(response!=4)&&(response!=5)&&(response!=6)){
cout<< "Please enter a valid choice (1 - 6): ";
cin >> response;
}
if(response==1){
addDepartment(dept);
}
else if(response==2){
//addEmployee(emp,dept);
}
else if(response==3){
}
else if(response==4){
}
else if(response==5){
//salaryReport(dept);
}
}
cout << "Thank you, goodbye.";
}
Why it breaks.
The addDepartment function never actually returns a department. When the function exits, the space where the return newly created Department would be is left uninitialized. This causes undefined behavior. The compiler tries to destruct the Department object like it normally would, but because it was never initialized, free gets called on garbage (causing the error).
We can fix this by adding a line to addDepartment returning the actual department:
Department addDepartment(Department dept[3]){
int repeat=0;
int counter=0;
if (counter>2){
cout<<"The array is full, you can not add any more Departments."<<endl;
}
else{
cout << "Please Enter Department Details:"<<endl;
cout << "Department ID : ";
cin >> dept[counter].departmentID;
for(int x=0; x<3; x++){
for (int y=x+1; y<3; y++){
if(dept[x].departmentID==dept[y].departmentID)
repeat++;
}
}
if(repeat!=0)
cout<<"Value must be unique!"<<endl;
else{
cout << "Department Name : ";
cin >> dept[counter].departmentName;
cout << "Head of Department : ";
cin >> dept[counter].departmentHead;
counter++;
}
}
return /* some department */;
}
Alternatively, you could make addDepartment void.
Other considerations. Don't pass raw C arrays to functions. It doesn't do what you intend.
If you want to pass a copy of an array, pass a std::array, which will be copied automatically:
Department addDepartment(std::array<Department, 3> dept);
If want to access the elements of an existing array, pass a pointer:
Department addDepartment(Department* dept, int count);
One problem that I see is that you are creating an array of 3 Department objects in main and assuming that you have 5 elements in initialID.
Change main to create an array of 5 Department objects.
int main()
{
Employee emp[5];
Department dept[5];
...

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?

Traversing a linked list with a structure inside

So I a linked list of 4 students and inside each node for the linked list is a structure that holds some data about the students. I want to traverse this linked list and print the data inside each of the structures. I can traverse the linked list expect all the data print is 0. Any help would be much appreciated.
#include<stdlib.h>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdlib>
using namespace std;
void displayGrades( struct Outer *O);
void calculateGrades(struct Outer *O);
void readGrades( struct Outer *O);
struct Inner{
int id;
string name;
double midterm1;
double midterm2;
double midtermTotal;
double lab_H;
double finalExam;
double total;
};
Inner i1;
struct Outer{
Inner data;
Outer *next;
};
struct Outer o1, o2, o3, o4;
int main()
{
readGrades(&o1);
calculateGrades(&o1);
displayGrades(&o1);
//o1.next = &o2;
/*
readGrades(&o2);
calculateGrades(&o2);
displayGrades(&o2);
//o2.next =&o3;
readGrades(&o3);
calculateGrades(&o3);
displayGrades(&o3);
//o3.next =&o4;
readGrades(&o4);
calculateGrades(&o4);
displayGrades(&o4);
//o4.next =NULL;
*/
Outer *ptro1;
ptro1 = new Outer;
Outer *ptro2;
ptro2 = new Outer;
Outer *ptro3;
ptro3 = new Outer;
Outer *ptro4;
ptro4 = new Outer;
Outer *head=ptro1;
ptro1->next = ptro2;
ptro2->next = ptro3;
ptro3->next = ptro4;
ptro4->next = NULL;
while(head!=NULL) // && i<=2)
{
cout<<"Student ID: "<<head->data.id<<endl;
cout<<"Student Midterm1: "<<head->data.midterm1<<endl;
cout<<"Student Midterm2: "<<head->data.midterm2<<endl;
cout<<"Student Labs and Homework: "<<head->data.lab_H<<endl;
cout<<"Student Final Exam: "<<head->data.finalExam<<endl;
head = head->next;
}
return 0;
}
void readGrades(struct Outer *O){
cout<<"Enter the student's id: "<<endl;
cin>>o1.data.id;
cout<<"Enter the student's midterm #1 grade: ";
cin>>o1.data.midterm1;
cout<<"Enter the student's midterm #2 grade: ";
cin>>o1.data.midterm2;
cout<<"Enter the student's lab and homework grade: ";
cin>>o1.data.lab_H;
cout<<"Enter the student's final exam grade: ";
cin>>o1.data.finalExam;
}
void displayGrades(struct Outer *O){
cout<<"The students final grade is: ";
if(O->data.total>=90)
{
cout<<"A"<<endl;
}
else if(O->data.total<=89 && O->data.total>=80)
{
cout<<"B"<<endl;
}
else if(O->data.total<=79 && O->data.total>=70)
{
cout<<"C"<<endl;
}
else if(O->data.total<=69 && O->data.total<60)
{
cout<<"F"<<endl;
}
}
void calculateGrades(struct Outer *O){
O->data.midtermTotal=(((O->data.midterm1/50)+(O- >data.midterm2/50))/2)*35;
O->data.lab_H=(O->data.lab_H/20)*25;
O->data.finalExam=(O->data.finalExam/100)*40;
O->data.total=O->data.midtermTotal+O->data.lab_H+O->data.finalExam;
//displayGrades();
}
In the below function you need to use O as you are passing it but you are using
o1 which will overwrite every time
void readGrades(struct Outer *O)
{
cout<<"Enter the student's id: "<<endl;
cin>>O->data.id;
cout<<"Enter the student's midterm #1 grade: ";
cin>>O->data.midterm1;
cout<<"Enter the student's midterm #2 grade: ";
cin>>O->data.midterm2;
cout<<"Enter the student's lab and homework grade: ";
cin>>O->data.lab_H;
cout<<"Enter the student's final exam grade: ";
cin>>O->data.finalExam;
}
You should create a constructor that initializes the member variables to 0. Most of compilers do not do that by default.
struct Inner{
Inner() : id(0),midterm1(0),midtermTotal(0), lab_H(0), finalExam(0), total(0)
{
}
int id;
string name;
double midterm1;
double midterm2;
double midtermTotal;
double lab_H;
double finalExam;
double total;
};

gets() & puts() not declared in scope in dev c++

This is my simple code for a bookshop
There is nothing wrong with the code. I am using DevC++ to run the code and after compling it gives out an error which says 'gets' was not declared in this scope & the same error for puts. Please help me.
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<iomanip>
#include<cstring>
using namespace std;
class Book
{
char *title,*author,*publisher,ans;
int price,quant,quant_ent;
public:
Book()
{
title = new char[50];
author = new char[50];
publisher = new char[50];
price = quant = quant_ent = 0;
}
void getdata()
{
cout<<"\nEnter The Title";
gets(title);
cout<<"\nEnter The Author";
gets(author);
cout<<"\nEnter The Publisher";
gets(publisher);
cout<<"\nEnter The Price";
cin>>price;
cout<<"\nEnter The Quantity";
cin>>quant;
}
void display()
{
cout<<setw(15)<<title<<setw(15)<<author<<setw(15)<<publisher<<setw(10)<<quant
<<setw(10)<<price;
}
void search(char search_title[],char search_author[])
{
if(strcmpi(author,search_author)==0)
{
if(strcmpi(title,search_title)==0)
{
cout<<"\nBook Found!";
cout<<"\nEnter The Quantity: ";
cin>>quant_ent;
if(quant_ent <= quant)
{
cout<<"\nThe Title is: ";
puts(title);
cout<<"\nThe Author is: ";
puts(author);
cout<<"\nThe Publisher is: ";
puts(publisher);
cout<<"\nPrice Of Single Copy: "<<price;
cout<<"\nTotal Price = "<<price*quant_ent;
quant = quant - quant_ent;
}
else
{
cout<<"\nSufficient Quantity Not Available!";
}
}
}
}
};
int main()
{
Book obj[10];
int i=0,ch;
char author[50],title[50];
for(;;)
{
cout<<"\n*******MENU********\n1)Enter Details\n2)Buy Book\n3)Display All Books\n4)Exit";
cin>>ch;
switch(ch)
{
case 1:
obj[i].getdata();
i++;
break;
case 2:
cout<<"\nEnter The Authors Name: ";
gets(author);
cout<<"\nEnter The Title: ";
gets(title);
for(int j=0;j<i;j++)
{
obj[j].search(title,author);
}
break;
case 3:
cout<<setw(15)<<"TITLE"<<setw(15)<<"AUTHOR"<<setw(15)<<"PUBLISHER"<<setw(15)<<"QUANTITY"<<setw(15)<<"PRICE";
cout<<"\n"<<setw(75)<<"-----------------------------------------------------------------------------------------------------";
for(int j=0;j<i;j++)
{
cout<<"\n";
obj[j].display();
}
case 4:
exit(1);
};
}
}
Because it's declared in stdio.h (cstdio in C++) header and you haven't included it.
But you shall not use gets. It's a hopelessly broken function. Use fgets instead. Even better, ditch the naked pointers to char arrays and use std::string class instead.