Getting compilation error: "identifier 'objUser' is undefined" in my main() function - c++

I'm trying to call the functions from my clsFamily class within the main, however, when I pass down the (&objUser) I get a message stating:
identifier 'objUser' is undefined
Edit: Sorry forgot to mention but I want a dynamic vector array that is manipulated based on the users choice.
Any help at all will be kindly appreciated as it is for an assignment that is due next Thursday xD
int UserChoice();
int UserChoice()
{
int iChoice = 0;
int iAdults = 0;
int iChildren = 0;
cout << "How many family members do you have? \n";
cin >> iChoice;
cout << "How many of these are adults? \n";
cin >> iAdults;
cout << "How many of these are children? \n";
cin >> iChildren;
return iChoice;
return iAdults;
return iChildren;
}
class clsUser
{
private:
string m_sName;
int m_iAge;
public:
void SetName(string);
string GetName();
void SetAge(int);
int GetAge();
clsUser();
~clsUser();
clsUser(string, int);
};
//This is to group the singular users into a group using a vector
class clsFamily
{
private:
vector <clsUser> objUser;
public:
void InputFamilyDetails(vector <clsUser> *objUser);
void OutputFamilyDetails(vector <clsUser> *objUser);
};
void clsFamily::InputFamilyDetails(vector <clsUser>* objUser)
{
string sName = "";
int iAge = 0;
for (int iCount = 0; iCount < objUser->size(); iCount++)
{
cout << "Please enter the name of family member " << iCount + 1 << "\n";
cin >> sName;
cout << "Please enter the age of family member " << iCount + 1 << "\n";
cin >> iAge;
objUser->at(iCount).SetName(sName);
objUser->at(iCount).SetAge(iAge);
}
}
//This is to allow the user to input the the details of the users from the vector
void clsFamily::OutputFamilyDetails(vector <clsUser>* objUser)
{
for (int iCount = 0; iCount < objUser->size(); iCount++)
{
cout << "The name of family member " << iCount + 1 << " is " << objUser->at(iCount).GetName() << " \n";
cout << "The age of family member " << iCount + 1 << " is " << objUser->at(iCount).GetAge()<< " \n";
}
}
int main()
{
clsFamily objFamily;
*//This is the area where the problem is occuring*
objFamily.InputFamilyDetails(&objUser);
objFamily.OutputFamilyDetails(&objUser);
}

clsFamily already has an objUser member. You shouldn't use it and not expect a parameter in InputFamiliyDetails and OutputFamilyDetails:
class clsFamily
{
private:
vector <clsUser> objUser; // Needs to be initialized with some size, though
public:
void InputFamilyDetails();
void OutputFamilyDetails();
};
void clsFamily::InputFamilyDetails()
{
string sName = "";
int iAge = 0;
for (int iCount = 0; iCount < objUser.size(); iCount++)
{
cout << "Please enter the name of family member " << iCount + 1 << "\n";
cin >> sName;
cout << "Please enter the age of family member " << iCount + 1 << "\n";
cin >> iAge;
objUser.at(iCount).SetName(sName);
objUser.at(iCount).SetAge(iAge);
}
}
void clsFamily::OutputFamilyDetails()
{
for (int iCount = 0; iCount < objUser.size(); iCount++)
{
cout << "The name of family member " << iCount + 1 << " is " << objUser.at(iCount).GetName() << " \n";
cout << "The age of family member " << iCount + 1 << " is " << objUser.at(iCount).GetAge()<< " \n";
}
}
int main()
{
clsFamily objFamily;
objFamily.InputFamilyDetails();
objFamily.OutputFamilyDetails();
}

Related

Why do I get the error "use of deleted function 'class : : class()"

#include <iostream>
using namespace std;
class student
{
protected:
string name;
int roll;
int age;
public:
student(string n, int r, int a)
{
name = n;
roll = r;
age = a;
}
};
class test : public student
{
protected:
int sub[5];
public:
void marks()
{
cout << "Enter marks in 5 subjects: " << endl;
cin >> sub[0] >> sub[1] >> sub[2] >> sub[3] >> sub[4];
}
void display()
{
cout << "Name : " << name << "\nRoll number : " << roll << "\nAge: " << age << endl;
cout << "Marks in 5 subjects : " << sub[0] << ", " << sub[1] << ", " << sub[2] << ", " << sub[3] << ", " << sub[4] << endl;
}
};
class sports
{
protected:
int sportmarks;
public:
sports(int sm)
{
sportmarks = sm;
}
};
class result : public test, public sports
{
int tot;
float perc;
public:
void calc()
{
tot = sportmarks;
for(int i = 0; i < 5; i++)
tot = tot + sub[i];
perc = (tot / 600.0) * 100;
cout << "Total: " << tot << "\nPercentage: " << perc << endl;
}
};
int main()
{
student ob1("Name", 781, 19);
sports ob2(78);
result ob;
ob.marks();
ob.display();
ob.calc();
}
I've been asked to use parameterized constructors to do this problem and notice I get these errors when I use constructors. Sorry if this post is inconvenient to read. In what way can I run this code while creating objects from parameterized constructors?
use of deleted function 'result::result()'
use of deleted function 'test::test()'.
no matching function for call to 'student::student()'
no matching function for call to 'sports::sports()'
student and sports have user-defined constructors, so the compiler does not generate default constructors for them.
test and result have no user-defined constructors, so the compiler will generate default constructors for them. However, since student and sports have no default constructors, the generated default constructors are marked delete'd as they are not usable. That is why you get errors.
To make your main() compile as-is, you need to define your own default constructors for test and result which pass explicit parameter values to their base classes, eg:
#include <iostream>
using namespace std;
class student
{
protected:
string name;
int roll;
int age;
public:
student(string n, int r, int a)
{
name = n;
roll = r;
age = a;
}
};
class test : public student
{
protected:
int sub[5];
public:
test() : student("", 0, 0) {}
void marks()
{
cout << "Enter marks in 5 subjects: " << endl;
cin >> sub[0] >> sub[1] >> sub[2] >> sub[3] >> sub[4];
}
void display()
{
cout << "Name : " << name << "\nRoll number : " << roll << "\nAge: " << age << endl;
cout << "Marks in 5 subjects : " << sub[0] << ", " << sub[1] << ", " << sub[2] << ", " << sub[3] << ", " << sub[4] << endl;
}
};
class sports
{
protected:
int sportmarks;
public:
sports(int sm)
{
sportmarks = sm;
}
};
class result : public test, public sports
{
int tot;
float perc;
public:
result() : test(), sports(0) {}
void calc()
{
tot = sportmarks;
for(int i = 0; i < 5; i++)
tot = tot + sub[i];
perc = (tot / 600.0) * 100;
cout << "Total: " << tot << "\nPercentage: " << perc << endl;
}
};
int main()
{
student ob1("Name", 781, 19);
sports ob2(78);
result ob;
ob.marks();
ob.display();
ob.calc();
}
Online Demo
However, this is not very useful, so I would suggest tweaking result's constructor to take the student and sports objects you have already created beforehand, and pass them to the base class copy constructors, which the compiler will generate for you, eg:
#include <iostream>
using namespace std;
class student
{
protected:
string name;
int roll;
int age;
public:
student(string n, int r, int a)
{
name = n;
roll = r;
age = a;
}
};
class test : public student
{
protected:
int sub[5];
public:
test(const student &s) : student(s) {}
void marks()
{
cout << "Enter marks in 5 subjects: " << endl;
cin >> sub[0] >> sub[1] >> sub[2] >> sub[3] >> sub[4];
}
void display()
{
cout << "Name : " << name << "\nRoll number : " << roll << "\nAge: " << age << endl;
cout << "Marks in 5 subjects : " << sub[0] << ", " << sub[1] << ", " << sub[2] << ", " << sub[3] << ", " << sub[4] << endl;
}
};
class sports
{
protected:
int sportmarks;
public:
sports(int sm)
{
sportmarks = sm;
}
};
class result : public test, public sports
{
int tot;
float perc;
public:
result(const student &s, const sports &sp) : test(s), sports(sp) {}
void calc()
{
tot = sportmarks;
for(int i = 0; i < 5; i++)
tot = tot + sub[i];
perc = (tot / 600.0) * 100;
cout << "Total: " << tot << "\nPercentage: " << perc << endl;
}
};
int main()
{
student ob1("Name", 781, 19);
sports ob2(78);
result ob(ob1, ob2);
ob.marks();
ob.display();
ob.calc();
}
Online Demo

List in C++ Standard Template Library (STL). I made the following program and I don't know how to make a function to print the list

#include <iostream>
#include <list>
#include <iterator>
using namespace std;
class Profesor
{
public:
string nume, departament;
int grad, vechime;
Profesor(string n, string d, int g, int v);
};
Profesor::Profesor(string n, string d, int g, int v) {
nume = n;
departament = d;
grad = g;
vechime = v;
}
int main()
{
list <Profesor*> profi;
Profesor* p;
int opt;
string nume, departament;
int grad, vechime;
do {
cout << "1.Adaugare" << endl;
cout << "Dati optiunea! " << endl;
cin >> opt;
switch (opt)
{
case 1:
cout << "Nume:";
cin >> nume;
cout << "Departament:";
cin >> departament;
cout << "Grad:";
cin >> grad;
cout << "Vechime";
cin >> vechime;
p = new Profesor(nume, departament, grad, vechime);
profi.push_front(p);
default:
break;
}
} while (opt);
return 0;
}
Option 1 is to add a new item into the list
This is the constructor of the class
So I need a function to display the entire list
ajgnsjdgn afkajkf nskjfnakfakfnaf afnakfnasdnlang akfnafdakfrnaasf asdfkasfna
ad akjdgnakjsgsa askfnaksd asgnaskdng asdgjnsadgag
Add a function to Profesor to output it's current variables:
void output() const {
cout << " * nume: " << nume << endl;
cout << " * departament: " << departament << endl;
cout << " * grad: " << grad << endl;
cout << " * vechime: " << vechime << endl;
}
Create a function that iterates through the list and calls this function.
Here is an example that uses a range based for loop:
void outputProfesors(const list<Profesor*>& profesors) {
for (const auto& profesor : profesors) {
profesor->output();
}
}
Call outputProfesors().

Array is getting trash after a new raw is added to a file ะก++ Visual Studio

I'm trying to solve a task with structs, dynamic arrays and files. So I'm
creating a dynamic array - Unit* array_of_employees = new Unit[number_of_employees];
generating an array - generateEmployees(Unit* array_of_employees, int& number_of_employees);
writing the data into the file - writeFileEmployees(Unit* array_of_employees, int number_of_employees);
showing elements of array in console - readAllEmployeeData(Unit* array_of_employees, int number_of_employees);
It is working correct till that moment. Then I'm
redistributing the array's memory by creating a new array with a +1 memory size - Unit* getRememberForArrayOfEmployees(Unit* array_of_employees, int& number_of_employees, int new_number_of_employees);
adding a new note in the end of the array
writing it in the end of the file - void writeEndFileEmployees(Unit new_epmloyee);
Then I'm trying to show the array in console, but there is trash in array. Need your help
#include <conio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
struct Unit
{
string fullName;
string department;
string position;
int monthSalary;
};
const string FILE_OF_EMPLOYEES = "employee.txt"; //file_path
int getCountOfEmployees(string FILE_OF_EMPLOYEES);
void generateEmployees(Unit* array_of_employees, int& number_of_employees);
void writeFileEmployees(Unit* array_of_employees, int number_of_employees);
void writeEndFileEmployees(Unit new_epmloyee);
void readAllEmployeeData(Unit* array_of_employees, int number_of_employees);
void addNewEmployeeData(Unit* array_of_employees, int& number_of_employees);
Unit* getRememberForArrayOfEmployees(Unit* array_of_employees, int& number_of_employees, int new_number_of_employees);
int main()
{
setlocale(LC_ALL, "rus");
int number_of_employees = getCountOfEmployees(FILE_OF_EMPLOYEES);
Unit* array_of_employees = new Unit[number_of_employees];
generateEmployees(array_of_employees, number_of_employees);
writeFileEmployees(array_of_employees, number_of_employees);
readAllEmployeeData(array_of_employees, number_of_employees);
addNewEmployeeData(array_of_employees, number_of_employees);
//From this place there is trash in the array_of_employees :(
readAllEmployeeData(array_of_employees, number_of_employees);
delete[]array_of_employees;
system("pause");
return 0;
}
//Define amount of structures in the file
int getCountOfEmployees(string FILE_OF_EMPLOYEES)
{
//Open and move a cursor in the end of the file
ifstream file(FILE_OF_EMPLOYEES, ios::in);
int number_of_strings = 0;
if (file.is_open())
{
string buffer;
while (getline(file, buffer))
number_of_strings++;
}
file.close();
return number_of_strings;
}
void generateEmployees(Unit* array_of_employees, int& number_of_employees)
{
number_of_employees = 1;
array_of_employees[0].fullName = "Ivanov";
array_of_employees[0].department = "QA1";
array_of_employees[0].position = "QA";
array_of_employees[0].monthSalary = 1000;
}
void writeFileEmployees(Unit* array_of_employees, int number_of_employees)
{
ofstream fout(FILE_OF_EMPLOYEES, ios::out);
for (int i = 0; i < number_of_employees; i++)
{
fout << array_of_employees[i].fullName << " "
<< array_of_employees[i].department << " "
<< array_of_employees[i].position << " "
<< array_of_employees[i].monthSalary;
if (i < number_of_employees - 1) fout << endl;
}
fout.close();
}
void writeEndFileEmployees(Unit new_employee)
{
ofstream fadd(FILE_OF_EMPLOYEES, ios::app);
fadd << endl;
fadd << new_employee.fullName << " "
<< new_employee.department << " "
<< new_employee.position << " "
<< new_employee.monthSalary;
fadd.close();
cout << "New employee added" << endl;
}
void readAllEmployeeData(Unit* array_of_employees, int number_of_employees)
{
//system("cls");
cout << " Users accounts\n"
<< " ------------------------------- \n"
<< "|Full Name"
<< "\t|Department"
<< "\t|Position"
<< "\t|Monthly Salary\t|\n"
<< "\n ------------------------------- \n";
for (int i = 0; i < number_of_employees; i++)
{
cout << "|" << array_of_employees[i].fullName << " "
<< "\t|" << array_of_employees[i].department << "\t"
<< "\t|" << array_of_employees[i].position << "\t"
<< "\t|" << array_of_employees[i].monthSalary << "\t|"
<< endl;
}
cout << " ------------------------------- " << endl;
}
void addNewEmployeeData(Unit* array_of_employees, int& number_of_employees)
{
//system("cls");
array_of_employees = getRememberForArrayOfEmployees(array_of_employees, number_of_employees, number_of_employees + 1);
cout << "Add new user profile\n" << endl;
cout << "Full Name: ";
cin >> array_of_employees[number_of_employees - 1].fullName;
cout << "Department: ";
cin >> array_of_employees[number_of_employees - 1].department;
cout << "Position: ";
cin >> array_of_employees[number_of_employees - 1].position;
cout << "Monthly salary: ";
cin >> array_of_employees[number_of_employees - 1].monthSalary;
writeEndFileEmployees(array_of_employees[number_of_employees - 1]);
}
Unit* getRememberForArrayOfEmployees(Unit* array_of_employees, int& number_of_employees, int new_number_of_employees)
{
Unit* new_array_of_employees;
if (number_of_employees < new_number_of_employees)
{
new_array_of_employees = new Unit[new_number_of_employees];
for (int i = 0; i < number_of_employees; i++)
{
new_array_of_employees[i].fullName = array_of_employees[i].fullName;
new_array_of_employees[i].department = array_of_employees[i].department;
new_array_of_employees[i].position = array_of_employees[i].position;
new_array_of_employees[i].monthSalary = array_of_employees[i].monthSalary;
}
for (int i = number_of_employees; i < new_number_of_employees; i++)
{
new_array_of_employees[i].fullName = " ";
new_array_of_employees[i].department = " ";
new_array_of_employees[i].position = " ";
new_array_of_employees[i].monthSalary = 0;
}
delete[]array_of_employees;
number_of_employees = new_number_of_employees;
array_of_employees = new_array_of_employees;
}
return array_of_employees;
}
addNewEmployeeData (via the call to getRememberForArrayOfEmployees) can delete the existing array_of_employees data. You allocate a new array for this, but never pass the modified pointer back to the caller.
You should pass array_of_employees as a reference (Unit *&array_of_employees) like you do with number_of_employees.

C++: Multiple definition of object error

I recently started with file structuring in C++ with little success. The project was split into following files
-groups.h
-groups.cpp
-people.h
-people.cpp
-main.cpp
There are 2 base classes, groups and players and every other class in inherited by either of them.
Here's the files
groups.h
people.h
groups.cpp
people.cpp
main.cpp
groups.h
#ifndef GROUPS_H
#define GROUPS_H
//Groups of people one of the base classes
class groups {
int num_of_people;
float avg_age;
friend class SoccerTeams;
public:
//virtual string getclass() { return char2str(typeid(*(this)).name()); }
groups(int numb = 0): num_of_people(numb) {};
~groups(){};
};
//SoccerTeam group class
class SoccerTeams : public groups {
std::string teamName;
std::vector<SoccerTeams> teams;
int teamId;
public:
Players player;
void addManager();
std::string nameTeam(int);
void deletePlayer(int);
void showTeam();
void addPlayer();
void showPlayers();
void showManagers();
void exportToFile(const char *);
SoccerTeams() {};
SoccerTeams(std::string, int);
~SoccerTeams() {};
};
//FanClub group class
class FanClubs : public groups{
std::string clubName;
int clubId;
std::vector<FanClubs> fanclubs;
public:
Fans fan;
void addFans();
void showFans();
FanClubs() {};
FanClubs(std::string, int);
~FanClubs() {};
};
#endif
groups.cpp
#include <algorithm>
#include <iostream>
#include <vector>
#include <typeinfo>
#include <boost/units/detail/utility.hpp>
#include <cstdlib>
#include <fstream>
#include <list>
#include "groups.h"
using namespace std;
//Fan Club member functions
FanClubs::FanClubs(string name, int id) {
clubName = name;
clubId = id;
fanclubs.push_back(*this);
};
void FanClubs::showFans() {
cout << "Players in " << fanclubs.begin() -> clubName << endl;
fan.showFanas();
}
void FanClubs::addFans() {
int choice = 0;
cout << "1. Add a bunch of fans\n2. Add custom fans\nChoice: ";
cin >> choice;
switch(choice) {
case 1: {
int requirement;
cout << "How many fans do you need: ";
cin >> requirement;
static const string names[] = {
"Margarita", "Amalia", "Sam", "Mertie", "Jamila", "Vilma",
"Mazie", "Margart", "Lindsay", "Kerstin", "Lula", "Corinna", "Jina",
"Jimmy", "Melynda", "Demetrius", "Beverly", "Olevia", "Jessika",
"Karina", "Abdallah", "Max", "Prateek", "Aghaid"
};
for (int i = 0; i < requirement; ++i) {
fan.name = names[rand() % 24];
fan.age = (rand() % 80 + 1);
fan.sex = ((rand() % 2) ? 'M' : 'F');
fan.under_auth = false;
fan.auth_level = 0;
fans.push_back(fan);
}
break;
}
case 2: {
int requirement;
cout << "How many fans you want to add?\nnumber: ";
cin >> requirement;
for (int i = 0; i < requirement; ++i) {
cout << "======Fan " << i + 1 << "=======\n";
cout << "Enter name: ";
cin >> fan.name;
cout << "Enter age: ";
cin >> fan.age;
cout << "Enter sex: ";
cin >> fan.sex;
fan.under_auth = false;
fan.auth_level = 0;
fans.push_back(fan);
}
break;
}
default:
cout << "Incorrect choice\n";
break;
}
}
//Soccer Teams member functions
string SoccerTeams::nameTeam(int id) {
return teams.begin() -> teamName;
}
void SoccerTeams::showPlayers() {
cout << "Players in " << teams.begin() -> teamName << endl;
player.showPlayas();
}
void SoccerTeams::showManagers() {
int counter = 1;
list<ManagingDirectors>::iterator i;
for (i = directors.begin(); i != directors.end(); i++) {
cout << "Director " << counter << endl;
cout << "Works for team " << nameTeam(i -> directorId) << endl;
cout << "Name: " << i -> name << endl;
cout << "Sex: " << i -> sex << endl;
counter++;
}
}
void SoccerTeams::addPlayer() {
int newId;
int number;
cout << "Number of players to be added: ";
cin >> number;
for (int i = 0; i < number; ++i) {
cout << "\nEnter player name: ";
cin >> player.name;
cout << "Enter sex(M/F): ";
cin >> player.sex;
cout << "Enter age: ";
cin >> player.age;
cout << "Enter player id(0 for random id): ";
cin >> newId;
newId == 0 ? player.playerId = (rand() % 100 + 1) : player.playerId = newId;
player.under_auth = true;
player.auth_level = 0;
players.push_back(player);
teams.begin()->num_of_people++;
}
}
void SoccerTeams::deletePlayer(int id) {
std::vector<Players>::iterator i;
for (i = players.begin(); i != players.end(); ) {
if(i->playerId == id) {
i = players.erase(i);
teams.begin()->num_of_people--;
}
else
i++;
}
}
void SoccerTeams::showTeam() {
vector<SoccerTeams>::iterator i;
for (i = teams.begin(); i != teams.end(); ++i) {
cout << "\nTeam name: " << i -> teamName << endl;
cout << "Team id: " << i -> teamId << endl;
cout << "Number of players: " << i -> num_of_people << endl;
cout << "Average age: " << i -> player.ageCalc()/teams.begin() -> num_of_people << endl;
}
}
SoccerTeams::SoccerTeams(string tn, int id) {
teamName = tn;
teamId = id;
teams.push_back(*this);
};
void SoccerTeams::addManager() {
ManagingDirectors mandir;
int number;
cout << "How many managers you want to add: ";
cin >> number;
for (int i = 0; i < number; i++) {
cout << "Manager " << i + 1 << endl;
cout << "Enter name of the director: ";
cin >> mandir.name;
cout << "Enter the age: ";
cin >> mandir.age;
cout << "Enter the sex(M/F): ";
cin >> mandir.sex;
mandir.directorId = teams.begin() -> teamId;
mandir.auth_level = 3;
mandir.under_auth = false;
directors.push_front(mandir);
}
}
void SoccerTeams::exportToFile(const char *filename) {
ofstream outfile;
outfile.open(filename, ios::out);
vector<Players>::iterator i;
int counter = 1;
outfile << "Team Data" << endl;
outfile << "Team name : " << teamName << "\nPlayers : " << teams.begin() -> num_of_people << endl;
outfile << "Average age: " << teams.begin() -> player.ageCalc()/teams.begin() -> num_of_people << endl;
for (i = players.begin(); i != players.end(); ++i) {
outfile << "\nPlayer " << counter << endl;
outfile << "Name: " << i -> name << endl;
outfile << "Sex : " << i -> sex << endl;
outfile << "Age : " << i -> age << endl;
outfile << "Pid : " << i -> playerId << endl;
counter++;
}
outfile.close();
}
people.h
#ifndef PEOPLE_H
#define PEOPLE_H
//People base class
class people {
string name;
char sex;
int age;
bool under_auth;
int auth_level;
friend class SoccerTeams;
friend class Players;
friend class Fans;
friend class FanClubs;
public:
//virtual string getclass() { return char2str(typeid(*(this)).name()); }
people(){};
~people(){};
//virtual int get_age(){ return this->age; };
};
//players class people
class Players : public people {
int playerId;
int avgAge;
friend class SoccerTeams;
public:
void showPlayas();
float ageCalc();
Players(){};
~Players(){};
};
std::vector<Players> players;
//Class Managing Directors people
class ManagingDirectors : public people {
int directorId;
friend class SoccerTeams;
public:
ManagingDirectors(int);
ManagingDirectors() {};
~ManagingDirectors(){};
};
std::list<ManagingDirectors> directors;
//Fans people class
class Fans : public people {
public:
void showFanas();
Fans(){};
~Fans(){};
};
std::vector<Fans> fans;
#endif
people.cpp
#include <algorithm>
#include <iostream>
#include <vector>
#include <typeinfo>
#include <boost/units/detail/utility.hpp>
#include <cstdlib>
#include <fstream>
#include <list>
#include "people.h"
using namespace std;
const int vector_resizer = 50;
string char2str(const char* str) { return boost::units::detail::demangle(str); }
//Fan class member functions
void Fans::showFanas() {
int counter = 1;
vector<Fans>::iterator i;
for (i = fans.begin(); i != fans.end(); ++i) {
cout << "\nFan " << counter << endl;
cout << "Name: " << i -> name << endl;
cout << "Sex: " << i -> sex << endl;
cout << "Age: " << i -> age << endl;
counter++;
}
}
//Players class member functions
float Players::ageCalc() {
int totalAge = 0;
vector<Players>::iterator i;
for (i = players.begin(); i != players.end(); ++i) {
totalAge += i->age;
}
return totalAge;
}
void Players::showPlayas() {
int counter = 1;
vector<Players>::iterator i;
for (i = players.begin(); i != players.end(); ++i) {
cout << "\nPlayer " << counter << endl;
cout << "Name: " << i -> name << endl;
cout << "Sex: " << i -> sex << endl;
cout << "Age: " << i -> age << endl;
cout << "Player id: " << i -> playerId << endl;
counter++;
}
}
//Member functions of Managing DIrectos
ManagingDirectors::ManagingDirectors(int number) {
directorId = number;
};
In addition to these files, I also have a makefile.
//makefile
footballmaker: main.o groups.o people.o
gcc -o main main.o groups.o people.o
rm groups.o people.o
Also here's all the code in one file, the way it works right now.
I'm getting the following error when I try to make the program,
gcc -o main main.o groups.o people.o
groups.o:(.bss+0x0): multiple definition of `players'
main.o:(.bss+0x0): first defined here
groups.o:(.bss+0x20): multiple definition of `directors[abi:cxx11]'
main.o:(.bss+0x20): first defined here
groups.o:(.bss+0x40): multiple definition of `fans'
main.o:(.bss+0x40): first defined here
people.o:(.bss+0x0): multiple definition of `players'
main.o:(.bss+0x0): first defined here
people.o:(.bss+0x20): multiple definition of `directors[abi:cxx11]'
main.o:(.bss+0x20): first defined here
people.o:(.bss+0x40): multiple definition of `fans'
main.o:(.bss+0x40): first defined here
...
collect2: error: ld returned 1 exit status
makefile:3: recipe for target 'footballmaker' failed
make: *** [footballmaker] Error 1
The entire error was over 400 lines long, it is attached here.
I'm not sure how I can include files, so that I don't duplicate them, since the files are needed to make the program work, would there be a better way to split my code into files?
You define (not just declare!) variables at file scope in header file people.h. Such a variable definition will be visible to all other translation units at time of linkage. If different translation units, e.g. people.cpp and main.cpp, now include people.h, then this is as if these variable definitions had been written directly into both people.cpp and main.cpp, each time defining a separate variable with the same name at a global scope.
To overcome this, declare the variables in the header file, but define it in only one translation unit, e.g. people.cpp. Just declaring a variable means putting keyword extern in front of it (telling the compiler that variable definition will be provided by a different translation unit at the time of linking):
// people.h
extern std::vector<Players> players;
extern std::list<ManagingDirectors> directors;
extern std::vector<Fans> fans;
// people.cpp
std::vector<Players> players;
std::list<ManagingDirectors> directors;
std::vector<Fans> fans;

Trying to make string array passed through methods C++

I'm trying to read names and ages from user, until user inputs "stop". Then just print all these values. Please help me , I'm just the beginner in C++
// Pass.cpp
// Reading names and ages from user and outputting them
#include <iostream>
#include <iomanip>
#include <cstring>
using std::cout;
using std::cin;
using std::endl;
using std::setw;
using std::strcmp;
char** larger(char** arr);
int* larger(int* arr);
void read_data(char*** names, int** ages);
void print_data(char*** names, int** ages);
int main()
{
char** names = new char*[5];
char*** p_names = &names;
int* ages = new int[5];
int** p_ages = &ages;
read_data(p_names,p_ages);
print_data(p_names,p_ages);
}
void read_data(char*** names, int** ages)
{
const char* sent = "stop";
const int MAX = 15;
int count = 0;
char UI[MAX];
cout << "Enter names and ages."
<< endl << "Maximum length of name is " << MAX
<< endl << "When stop enter \"" << sent << "\".";
while (true)
{
cout << endl << "Name: ";
cin.getline(UI,MAX,'\n');
if (!strcmp(UI, sent))
break;
if (count + 1 > sizeof (&ages) / sizeof (&ages[0]))
{
*names = larger(*names);
*ages = larger(*ages);
}
*names[count] = UI;
cout << endl << "Age: ";
cin >> *ages[count++];
}
}
void print_data(char*** names, int** ages)
{
for (int i = 0; i < sizeof(*ages) / sizeof(*ages[0]);i++)
{
cout << endl << setw(10) << "Name: " << *names[i]
<< setw(10) << "Age: " << *ages[i];
}
}
char** larger(char** names)
{
const int size = sizeof(names) / sizeof(*names);
char** new_arr = new char*[2*size];
for (int i = 0; i < size; i++)
new_arr[i] = names[i];
return new_arr;
}
int* larger(int* ages)
{
const int size = sizeof(ages) / sizeof(*ages);
int* new_arr = new int[2 * size];
for (int i = 0; i < size; i++)
new_arr[i] = ages[i];
return new_arr;
}
You are really over complicating things.
Given the original problem:
Write a program that reads a number (an integer) and a name (less than
15 characters) from the keyboard. Design the program so that the data
is done in one function, and the output in another. Store the data in
the main() function. The program should end when zero is entered for
the number. Think about how you are going to pass the data between
functions
The problem wants you to think about passing parameters to functions. A simple solution would be:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
// Pass in a char array and an integer reference.
// These values will be modified in the function
void read_data(char name[], int& age)
{
cout << endl << "Age: ";
cin >> age;
cin.ignore();
cout << endl << "Name: ";
cin.getline(name, 16);
}
// Pass a const array and an int value
// These values will not be modified
void print_data(char const *name, int age)
{
cout << endl << setw(10) << "Name: " << name
<< setw(10) << "Age: " << age;
}
int main()
{
char name[16];
int age;
cout << "Enter names and ages."
<< endl << "Enter 0 age to quit.";
do {
read_data(name, age);
print_data(name, age);
} while (0 != age)
}
EDIT: Modified per user3290289's comment
EDIT2: Storing data in an array
// Simplify by storing data in a struct (so we don't have to manage 2 arrays)
struct Person {
char name[16];
int age;
};
// Returns how many People were input
int read_data(Person*& arr)
{
int block = 10; // How many persons to allocate at a time
arr = NULL;
int arr_size = 0;
int index = 0;
while (true) {
if (index == arr_size) {
arr_size += block;
arr = (Person *)realloc(arr, arr_size * sizeof(Person)); // Reallocation
// Should check for error here!
}
cout << endl << "Age: ";
cin >> arr[index].age;
cin.ignore();
if (0 == arr[index].age) {
return index;
}
cout << endl << "Name: ";
cin.getline(arr[index++].name, 16);
}
}
void print_data(Person *arr, int count)
{
for (int i = 0; i < count; i++) {
cout << endl << setw(10) << "Name: " << arr[i].name
<< setw(10) << "Age: " << arr[i].age;
}
}
int main()
{
Person *arr;
int count = read_data(arr);
print_data(arr, count);
free(arr); // Free the memory
}
try this:
#include <iostream>
#include <iomanip>
#include <vector>
#include <sstream>
using std::cout;
using std::cin;
using std::endl;
using std::setw;
using std::strcmp;
void read_data(std::vector<std::string> &names, std::vector<int> &ages);
void print_data(std::vector<std::string> &names, std::vector<int> &ages);
int main()
{
std::vector<std::string> names;
std::vector<int> ages;
read_data(names, ages);
print_data(names, ages);
}
void read_data(std::vector<std::string> &names, std::vector<int> &ages)
{
const char* sent = "stop";
cout << "Enter names and ages."
<< endl << "When stop enter \"" << sent << "\".";
while (true)
{
std::string input;
cout << endl << "Name: ";
std::getline(cin, input);
if (!strcmp(input.c_str(), sent))
break;
names.push_back(input);
cout << endl << "Age: ";
std::string age;
std::getline(cin, age);
ages.push_back(atoi(age.c_str()));
}
}
void print_data(std::vector<std::string> &names, std::vector<int> &ages)
{
for (int i = 0; i < names.capacity() ; i++)
{
cout << endl << setw(10) << "Name: " << names.at(i)
<< setw(10) << "Age: " << ages.at(i);
}
}
One problem I see is this if statement:
if (count + 1 > sizeof (&ages) / sizeof (&ages[0]))
&ages is the address of an int**, a pointer, and so it's size is 8 (usually) as that is the size of a pointer type. The function does not know the size of the array, sizeof will only return the correct answer when ages is declared in the same scope.
sizeof(&ages) / sizeof(&ages[0])
will always return 1
I believe one natural solution about this problem is as follows:
create a "std::map" instance. Here std::map would sort the elements according to the age. Here my assumption is after storing the data into the container, you would like to find about a particular student age/smallest/largest and all various manipulation with data.Just storing and printing the data does not make much sense in general.
create a "std::pair" and take the both input from the user into the std::pair "first" and "second" member respectively. Now you can insert this "std::pair" instance value into the above "std::map" object.
While printing, you can now fetch the each element of "std::map" in the form of "std::pair" and then you can display pair "first" and "second" part respectively.