Transform c++ class private variables to public - c++

I am a first year student of programming, and I need some help.
I have code with public class but I need to change public to private. And it doesn't work for me. Maybe somebody can help me with some suggestions? Here's my working code with public objects, but I need to private. How can I do that?
This is my class's files:
Klientas.h:
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
class Klientas
{
public:
string vardas;
double lesos;
};
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
Klipas.h :
class Klipas
{
public:
string produktas;
string grupe;
double trukme;
double krastine1;
double krastine2;
double plotas;
double klipoSekKaina;
double klipoKaina;
};
My code:
Lab_1.cpp
#include "Klipas.h"
#include "Klientas.h"
using namespace std;
//---------------------------------------------
int main() {
setlocale(LC_ALL, "Lithuanian");
Klipas K[100];
int na;
Klientas kl;
// Iš failo fv įveda duomenis į objektų masyvą K(kiek).
ĮvestiDuomenis("Duomenys.txt", K, na);
SpausdintiDuomenis("Rezultatai.txt", K, na);
}
void ĮvestiDuomenis(string fv, Klipas K[], int & kiek) {
ifstream fd ("Duomenys.txt");
fd >> kiek;
fd.ignore();
for (int i = 0; i < kiek; i++) {
getline(fd, K[i].produktas, ','); fd >> ws;
fd >> K[i].grupe;
fd >> K[i].trukme;
fd >> K[i].krastine1;
fd >> K[i].krastine2;
fd >> K[i].klipoSekKaina;
fd.ignore();
}
fd.close();
// cout << "Programa baigė darbą\n";
}
// Objektų masyvo K(kiek) reikšmes spausdina lentele į failą fv
void SpausdintiDuomenis(string fv, Klipas K[], int kiek) {
ofstream fr("Rezultatai.txt", ios::app);
fr.setf(ios::fixed); fr.setf(ios::left);
cout << "Klipų skaičius: " << kiek << endl;
cout << "Klipų sąrašas:\n";
cout << "----------------------------------------------------\n";
cout << "| Produktas | Grupė | Klipo trukmė(s) | 1 Kraštinė(cm) | 2 Kraštinė(cm) | Klipo sekundės kaina(Eur/s) | \n";
cout << "----------------------------------------------------\n";
for (int i = 0; i < kiek; i++) {
cout << "| " << setw(10) << K[i].produktas << "| " << K[i].grupe
<< setprecision(0) << setw(10) << "| " << K[i].trukme << "| " << setw(15) << K[i].krastine1 << "| " << setw(10) << K[i].krastine2 << "| " << setw(10) << K[i].klipoSekKaina << endl;
}
{
cout << "-------------------------------\n";
cout << "Klipo Kava plotas:" << K[0].krastine1*K[0].krastine2 << " " << "cm2" << endl;
cout << "Klipo Obuolys plotas:" << K[1].krastine1*K[1].krastine2 << " " << "cm2" << endl;
cout << "Klipo Sultys plotas:" << K[2].krastine1*K[2].krastine2 << " " << "cm2" << endl;
cout << "-------------------------------\n";
}
string ilg_trukme; // randame kuris klipas yra ilgiausias
if (K[0].trukme > K[1].trukme) {
ilg_trukme = K[0].produktas;
} else if (K[1].trukme > K[2].trukme) {
ilg_trukme = K[1].produktas;
} else {
ilg_trukme = K[2].produktas;
}
cout << "Ilgiausias klipas: " << ilg_trukme << endl;
cout << "-------------------------------\n";
{
K[0].klipoKaina = K[0].trukme * K[0].klipoSekKaina;
K[1].klipoKaina = K[1].trukme * K[1].klipoSekKaina;
K[2].klipoKaina = K[2].trukme * K[2].klipoSekKaina;
cout << "Klipo Kava Kaina:" << K[0].klipoKaina << " " << "Eur." << endl;
cout << "Klipo Obuolys Kaina:" << K[1].klipoKaina << " " << "Eur." << endl;
cout << "Klipo Sultys Kaina:" << K[2].klipoKaina << " " << "Eur." << endl;
cout << "-------------------------------\n";
}
{
string brangiausias_klipas; //randame kuris klipas brangiausias
double br_kl;
Klientas kl;
if (K[0].klipoKaina > K[1].klipoKaina && K[0].klipoKaina > K[2].klipoKaina ) {
brangiausias_klipas = K[0].produktas;
br_kl = K[0].klipoKaina;
} else if (K[1].klipoKaina > K[2].klipoKaina) {
brangiausias_klipas = K[1].produktas;
br_kl = K[1].klipoKaina;
} else {
brangiausias_klipas = K[2].produktas;
br_kl = K[2].klipoKaina;
}
cout << "Brangiausias klipas yra: " << brangiausias_klipas << endl;
cout << "-------------------------------\n";
cout << "Kiek jūs turite pinigų? " << endl; //kliento turimos pajamos
cin >> kl.lesos ;
cout << "-------------------------------\n";
//Randame kuriuos klipus klientas glaėtų įsigyti su savo pajamom
{
if(kl.lesos < K[0].klipoKaina && kl.lesos < K[1].klipoKaina && kl.lesos < K[2].klipoKaina) {
cout << "Jūs negalite nusipikrti nei vieno klipo " << endl;
} else {
if(kl.lesos >= K[0].klipoKaina) {
cout << "Jūs galite nusipirkti klipą " << K[0].produktas << endl;
}
if (kl.lesos >= K[1].klipoKaina) {
cout << "Jūs galite nusipirkti klipą " << K[1].produktas << endl;
}
if (kl.lesos >= K[2].klipoKaina) {
cout << "Jūs galite nusipirkti klipą " << K[2].produktas << endl;
}
}
}
}
}

Your teacher probably wants you to use getters.
In:
class Klipas
{
public:
string produktas;
string grupe;
double trukme;
double krastine1;
double krastine2;
double plotas;
double klipoSekKaina;
double klipoKaina;
};
You want to have access to all these members, but prevent external changes.
So you can change your code to:
class Klipas
{
public:
string GetProduktas() {return produktas;}
string Getgrupe() {return grupe;}
double Gettrukme() {return trukme;}
double Getkrastine1() {return krastine1;}
double Getkrastine2() {return krastine2;}
double Getplotas() {return plotas;}
double GetklipoSekKaina(){return klipoSekKaina;}
double GetklipoKaina() {return klipoKaina;}
private:
string produktas;
string grupe;
double trukme;
double krastine1;
double krastine2;
double plotas;
double klipoSekKaina;
double klipoKaina;
};
and use those getters instead of the objects themselves in your function:
fd >> K[i].Getgrupe();
fd >> K[i].Gettrukme();
fd >> K[i].Getkrastine1();
fd >> K[i].Getkrastine2();
fd >> K[i].GetklipoKaina();
As for setters go, you can either set your values in the constructor, or implement the same way:
public:
void SetProduktas(string prdkt) {produktas = prdkt;}

You can rewrite your class variables to be private and then use getters and setters to modify them.
class C {
private:
int id;
public:
int get_id() { return this->id; }
void set_id(int newId) { this->id = newId; }
};
Or you can make private class inside of another class
class A {
private:
class D {};
};

Related

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().

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;

Doesn't seem to be working using ifstream fin; and fin.open("filename");

I have a program for my class to read in information from a file, as an array, using a function and I've coded this the same way I did for classes last year and I'm not sure why it's not working. I'm supposed to also add more to this but wanted to try to figure out why it's not working with what it already has.
I don't think it's reading the file in because nothing comes out on the output file or the window that pops up when it runs.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
const int maxs = 50;
struct stype
{
int crn;
string name;
int crhrs;
int numstu;
int stucrhrs;
string prof;
};
stype initrec = { 0.0, "course", 0.0, 0.0, 0.0, "prof" };
void initem(stype p[], int &numc)
{
int i;
for (i = 0; i < maxs; i++) p[i] = initrec;
numc = 0;
}
void readem(stype p[], int &numc)
{
int i = 0;
ifstream fin;
fin.open("program1.dat");
while (!fin.eof())
{
fin >> p[i].crn >> p[i].name >> p[i].crhrs >> p[i].numstu >> p[i].stucrhrs >> p[i].prof;
i++;
}
numc = i;
cout << "readem reached " << endl;
}
void printem(stype p[], int &numc, ofstream &fout)
{
int i;
for (i = 0; i < numc; i++)
{
fout << left << setw(10) << p[i].crn << left << setw(15) << p[i].name << left
<< setw(15) << p[i].numstu << right << setw(2) << p[i].crhrs << right <<
setw(2) << p[i].stucrhrs << right << setw(10) << p[i].prof << endl;
}
cout << "printem reached " << endl;
}
void swapem(stype &a, stype &b)
{
stype temp;
temp = a;
a = b;
b = temp;
cout << "swapem reached " << endl;
}
void sortem()
{
cout << "sortem reached " << endl;
}
void getaverage()
{
cout << "getaverage reached " << endl;
}
void credithours()
{
cout << "Credit hours totalled. " << endl;
}
void main()
{
int crn[maxs], crhrs[maxs], stucrhrs[maxs];
string name[maxs], prof[maxs];
stype p[maxs];
int numc;
ofstream fout;
fout.open("program1.out");
fout.setf(ios::fixed);
fout.precision(2);
initem(p, numc);
readem(p, numc);
printem(p, numc, fout);
getaverage();
sortem();
printem(p, numc, fout);
system("pause");
}

The code is printing the same values when it should be randomly generating each ovr and also it is not printing the first value in the array

The issue that I am having is that with the code below, each plOvr for all of the class objects is the same. This causes them to have the same stats for everything. Also, I have an array with names that should be printed but it is skipping the first value.
using namespace std;
class Player
{
public:
int plOvr;
float plSpg, plSps;
string werk;
void setPlayeName(string);
string plName;
void setPlyrVal()
{
srand (time(NULL));
plOvr = rand()% 29 + 70;
plSps = plOvr / 10;
plSpg = plSps / 2;
}
};
void Player::setPlayeName(string werk)
{
plName = werk;
}
int main()
{
Player plyr1,plyr2,plyr3,plyr4,plyr5;
string firstTime;
string name[5] = {"Eric Gelinas","John Merill", "Jaromir Jagr", "Travis Zajac","Reid Boucher"};
bool firstOp;
cout << "Is this the first time this program has run?" << endl;
cin >> firstTime;
if (firstTime == "Yes" || firstTime == "yes")
{
firstOp == firstOp;
plyr1.setPlyrVal();
plyr1.setPlayeName(name[1]);
plyr2.setPlyrVal();
plyr2.setPlayeName(name[2]);
plyr3.setPlyrVal();
plyr3.setPlayeName(name[3]);
plyr4.setPlyrVal();
plyr4.setPlayeName(name[4]);
plyr5.setPlyrVal();
plyr5.setPlayeName(name[5]);
ofstream playerSaveData;
playerSaveData.open ("savedata.txt");
playerSaveData << plyr1.plName << "," << plyr1.plOvr << "," << plyr1.plSpg << "," << plyr1.plSps << "\n";
playerSaveData << plyr2.plName << "," << plyr2.plOvr << "," << plyr2.plSpg << "," << plyr2.plSps << "\n";
playerSaveData << plyr3.plName << "," << plyr3.plOvr << "," << plyr3.plSpg << "," << plyr3.plSps << "\n";
playerSaveData << plyr4.plName << "," << plyr4.plOvr << "," << plyr4.plSpg << "," << plyr4.plSps << "\n";
playerSaveData << plyr5.plName << "," << plyr5.plOvr << "," << plyr5.plSpg << "," << plyr5.plSps << "\n";
playerSaveData.close();
cout << "done.\n";
}
else
{
firstOp == !firstOp;
}
return 0;
}
You may use std::uniform_int_distribution<int> and an engine as std::mt19937 from <random>.
The engine (as srand) has to be initialized with seed only once.
Your program rewritten:
#include <ctime>
#include <iostream>
#include <fstream>
#include <string>
#include <random>
class Player
{
public:
void setPlayeName(const std::string& name) { plName = name; }
void setPlyrVal(std::mt19937& rand_engine)
{
std::uniform_int_distribution<int> distr(70, 98);
plOvr = distr(rand_engine);
plSps = plOvr / 10;
plSpg = plSps / 2;
}
public:
int plOvr;
float plSpg, plSps;
std::string werk;
std::string plName;
};
int main()
{
std::mt19937 rand_engine(time(nullptr));
Player plyrs[5];
const std::string names[5] = {"Eric Gelinas","John Merill", "Jaromir Jagr", "Travis Zajac","Reid Boucher"};
std::cout << "Is this the first time this program has run?" << std::endl;
std::string firstTime;
std::cin >> firstTime;
if (firstTime == "Yes" || firstTime == "yes") {
for (int i = 0; i != 5; ++i) {
plyrs[i].setPlyrVal(rand_engine);
plyrs[i].setPlayeName(names[i]);
}
std::ofstream playerSaveData;
playerSaveData.open ("savedata.txt");
for (const auto& plyr : plyrs) {
playerSaveData << plyr.plName << "," << plyr.plOvr << "," << plyr.plSpg << "," << plyr.plSps << "\n";
}
std::cout << "done." << std::endl;
}
return 0;
}
Live example
You should call srand() only once in the whole program, instead of calling it before each rand().

c++ tic tac toe with coard.h board.cpp player.h player.cpp game.h game.cpp and main.cpp I want to make some changes

I've been using this code for my TicTacToe game but I want to make some changes:
first I want to introduce the name of the players, and when one of them wins, it appears on the message.
second, I want to introduce a ranking table of records, winning games and tied ones
third I want the table to be static, doesn't change in every move.
forth I want the table to have always the numbers in the square that each of them represent, and when someone chooses that position, it replaces the number for the pieace, X or O.
Now I'll post the code above of every file:
Player.h
#ifndef PLAYER_H
#define PLAYER_H
class Board;
class Player
{
public:
Player();
char GetPiece() const;
void MakeMove(Board& aBoard) const;
private:
static const int NUM_PIECES = 2;
static const char PIECES[NUM_PIECES];
static int current;
char m_Piece;
};
#endif
Player.cpp
#include "player.h"
#include "board.h"
#include <iostream>
using namespace std;
const char Player::PIECES[NUM_PIECES] = {'X', 'O'};
int Player::current = 0;
Player::Player()
{
m_Piece = PIECES[current];
current = (current + 1) % NUM_PIECES;
}
char Player::GetPiece() const
{
return m_Piece;
}
void Player::MakeMove(Board& aBoard) const
{
int move;
do
{
cout << "Player " << GetPiece();
cout << ", where would you like to move? (0-8): ";
cin >> move;
} while (!aBoard.IsLegalMove(move));
aBoard.ReceiveMove(GetPiece(), move);
}
Board.h
#ifndef BOARD_H
#define BOARD_H
class Board
{
public:
Board();
bool IsFull() const;
bool IsLegalMove(int move) const;
bool IsWinner(char piece) const;
void Display() const;
void Reset();
void ReceiveMove(char piece, int move);
static const int NUM_SQUARES = 9;
static const char EMPTY = ' ';
private:
static const int NUM_COMBOS = 8;
static const int NUM_IN_COMBO = 3;
static const int WINNING_COMBOS[NUM_COMBOS]
[NUM_IN_COMBO];
char m_Squares[NUM_SQUARES];
};
#endif
Board.cpp
#include "board.h"
#include <iostream>
using namespace std;
const int Board::WINNING_COMBOS[NUM_COMBOS]
[NUM_IN_COMBO] = { {0, 1, 2},{3, 4, 5},{6, 7, 8},{0, 3, 6},{1, 4, 7},{2, 5, 8},{0, 4, 8}, {2, 4, 6} };
Board::Board()
{
Reset();
}
bool Board::IsFull() const
{
bool full = true;
int i = 0;
while (full && i < NUM_SQUARES)
{
if (m_Squares[i] == EMPTY)
{
full = false;
}
++i;
}
return full;
}
bool Board::IsLegalMove(int move) const
{
return (move >= 0 && move < NUM_SQUARES && m_Squares[move] == EMPTY);
}
bool Board::IsWinner(char piece) const
{
bool winner = false;
int i = 0;
while (!winner && i < NUM_COMBOS)
{
int piecesInCombo = 0;
for (int j = 0; j < NUM_IN_COMBO; ++j)
{
if (m_Squares[WINNING_COMBOS[i][j]] == piece)
{
++piecesInCombo;
}
}
if (piecesInCombo == NUM_IN_COMBO)
{
winner = true;
}
++i;
}
return winner;
}
void Board::Display() const
{
cout << endl << "\t" << m_Squares[0] << " | " << m_Squares[1];
cout << " | " << m_Squares[2];
cout << endl << "\t" << "---------";
cout << endl << "\t" << m_Squares[3] << " | " << m_Squares[4];
cout << " | " << m_Squares[5];
cout << endl << "\t" << "---------";
cout << endl << "\t" << m_Squares[6] << " | " << m_Squares[7];
cout << " | " << m_Squares[8];
cout << endl << endl;
}
void Board::Reset()
{
for (int i=0; i<NUM_SQUARES; ++i)
{
m_Squares[i] = EMPTY;
}
}
void Board::ReceiveMove(char piece, int move)
{
m_Squares[move] = piece;
}
Game.h
#ifndef GAME_H
#define GAME_H
#include "board.h"
#include "player.h"
class Game
{
public:
Game();
bool IsPlaying() const;
bool IsTie() const;
void DisplayInstructions() const;
void NextPlayer();
void AnnounceWinner() const;
void Play();
private:
static const int NUM_PLAYERS = 2;
static const int FIRST = 0;
static const int SECOND = 1;
Board m_Board;
Player m_Players[NUM_PLAYERS];
int m_Current;
};
#endif
Game.cpp
#include "game.h"
#include <iostream>
using namespace std;
Game::Game():
m_Current(FIRST)
{}
bool Game::IsPlaying() const
{
return ( !m_Board.IsFull() &&!m_Board.IsWinner(m_Players[FIRST].GetPiece()) &&
!m_Board.IsWinner(m_Players[SECOND].GetPiece()) );
}
bool Game::IsTie() const
{
return ( m_Board.IsFull() &&!m_Board.IsWinner(m_Players[FIRST].GetPiece()) &&
!m_Board.IsWinner(m_Players[SECOND].GetPiece()) );
}
void Game::DisplayInstructions() const
{
cout << "\tWelcome to the ultimate intellectual
showdown: Tic-Tac-Toe.";
cout << endl << endl;
cout << "Make your move by entering a number,
0 - 8. The number" << endl;
cout << "corresponds with board position, as
illustrated:" << endl << endl;
cout << endl << "\t" << "0 | 1 | 2";
cout << endl << "\t" << "---------";
cout << endl << "\t" << "3 | 4 | 5";
cout << endl << "\t" << "---------";
cout << endl << "\t" << "6 | 7 | 8";
cout << endl << endl << "Prepare yourself. The
battle is about to begin.";
cout << endl << endl;
}
void Game::NextPlayer()
{
m_Current = (m_Current + 1) % NUM_PLAYERS;
}
void Game::AnnounceWinner() const
{
cout << "The raging battle has come to a fi nal end.";
cout << endl;
if (IsTie())
{
cout << "Sadly, no player emerged victorious.";
cout << endl;
}
else
{
cout << "The winner of this climatic ";
cout << "confrontation is Player ";
if (m_Board.IsWinner(m_Players[FIRST].
GetPiece()))
{
cout << m_Players[FIRST].GetPiece() << "!";
cout << endl;
}
else
{
cout << m_Players[SECOND].GetPiece() << "!";
cout << endl;
}
}
}
void Game::Play()
{
m_Current = FIRST;
m_Board.Reset();
while (IsPlaying())
{
m_Board.Display();
m_Players[m_Current].MakeMove(m_Board);
NextPlayer();
}
m_Board.Display();
AnnounceWinner();
}
main.cpp
#include "game.h"
#include <iostream>
using namespace std;
int main()
{
Game ticTacToe;
ticTacToe.DisplayInstructions();
char again;
do
{
ticTacToe.Play();
cout << endl << "Play again? (y/n): ";
cin >> again;
} while (again != 'n');
return 0;
}
I'm not going to write code for you, but I'm slightly bored at the moment so I will structure it somewhat so you have an idea.
You need to store the name per player, and some way to retrieve it for the winning playerwhen the game is finished.
You need to keep track of scores, store between sessions which means file i/o.
I don't understand what you want with 3 or 4.
Mi version en español y ademas lo mejoré un poquito
main.cpp
#include "Arbitro.h"
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int main()
{
system("color 09");
Arbitro Triqui;
Triqui.mostrarInstrucciones();
string continuar;
cout<<"\t\t\t\t presione cualquier tecla para continuar";
continuar = (char)getch();
system("cls");
char deNuevo;
do
{
Triqui.jugar();
cout << endl << "\t\t\tQuieres jugar otra vez? (s/n): ";
cin >> deNuevo;
system ("cls");
} while (deNuevo != 'n');
cout << endl;
cout << "\t\t\t\t/////////////////////////////////////////////////////\n";
cout << "\t\t\t\t// Autor: //\n";
cout << "\t\t\t\t// //\n";
cout << "\t\t\t\t// Camilo Andres Granda Codigo: 201759710 //\n";
cout << "\t\t\t\t// //\n";
cout << "\t\t\t\t/////////////////////////////////////////////////////\n";
cout << endl;
return 0;
}
Arbitro.h
#ifndef ARBITRO_H
#define ARBITRO_H
#include "Tablero.h"
#include "Jugador.h"
class Arbitro
{
public:
Arbitro();
bool enJuego() const;
bool empate() const;
void mostrarInstrucciones() const;
void siguienteJugador();
void anunciarGanador() const;
void jugar();
private:
static const int numero_de_jugadores = 2;
static const int primero = 0;
static const int segundo = 1;
Tablero m_Tablero;
Jugador m_Jugadores[numero_de_jugadores];
int m_Actual;
};
#endif
Arbitro.cpp
#include "Arbitro.h"
#include <iostream>
using namespace std;
Arbitro::Arbitro():
m_Actual(primero)
{}
bool Arbitro::enJuego() const
{
return ( !m_Tablero.estaLleno()
&&!m_Tablero.ganador(m_Jugadores[primero].getPieza()) &&
!m_Tablero.ganador(m_Jugadores[segundo].getPieza()) );
}
bool Arbitro::empate() const
{
return ( m_Tablero.estaLleno()
&&!m_Tablero.ganador(m_Jugadores[primero].getPieza()) &&
!m_Tablero.ganador(m_Jugadores[segundo].getPieza()) );
}
void Arbitro::mostrarInstrucciones() const
{
cout << "\t\t\t
///////////////////////////////////////////////////////\n";
cout << "\t\t\t // Bienvenidos
//\n";
cout << "\t\t\t
///////////////////////////////////////////////////////\n";
cout << endl << endl;
cout << "\t\t\tHaga su movimiento ingresando un numero, [1 - 9]. El numero"
<< endl;
cout << "\t\t\tcorresponde con la posicion de la tabla, como se ilustra:" <<
endl << endl;
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| 1 | 2 | 3 |";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| 4 | 5 | 6 |";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| 7 | 8 | 9 |";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << endl << "\t\t\t\tPreparate. La partida esta a punto de
comenzar.";
cout << endl << endl;
}
void Arbitro::siguienteJugador()
{
m_Actual = (m_Actual + 1) % numero_de_jugadores;
}
void Arbitro::anunciarGanador() const
{
if (empate())
{
cout << "\t\t\tEmpate, ningun jugador gano.";
cout << endl;
}
else
{
cout << "\t\t\tEl ganador de esta partida es el jugador ";
if (m_Tablero.ganador(m_Jugadores[primero].
getPieza()))
{
cout << m_Jugadores[primero].getPieza() << "!";
cout << endl;
}
else
{
cout << m_Jugadores[segundo].getPieza() << "!";
cout << endl;
}
}
}
void Arbitro::jugar()
{
m_Actual = primero;
m_Tablero.reiniciarTablero();
while (enJuego())
{
m_Tablero.mostrarTablero();
m_Jugadores[m_Actual].hacerMovimiento(m_Tablero);
siguienteJugador();
}
m_Tablero.mostrarTablero();
anunciarGanador();
}
Jugador.h
#ifndef JUGADOR_H
#define JUGADOR_H
#include <iostream>
#include <string> // string, stoi
#include <cctype> // isdigit
#include <cstdlib> // atoi
class Tablero;
class Jugador
{
public:
Jugador();
char getPieza() const;
void hacerMovimiento(Tablero& unTablero) const;
private:
static const int numero_de_fichas = 2;
static const char fichas[numero_de_fichas];
static int actual;
char m_Ficha;
};
#endif
Jugador.cpp
#include "Jugador.h"
#include "Tablero.h"
#include <iostream>
using namespace std;
const char Jugador::fichas[numero_de_fichas] = {'N', 'B'};
int Jugador::actual = 0;
Jugador::Jugador()
{
m_Ficha = fichas[actual];
actual = (actual + 1) % numero_de_fichas;
}
char Jugador::getPieza() const
{
return m_Ficha;
}
void Jugador::hacerMovimiento(Tablero& unTablero) const
{
string linea;
int move;
do
{
cout << "\t\t\tJugador " << getPieza() << ", Donde te gustaria hacer el movimiento? [1 - 9]: ";
cin >> linea;
if (unTablero.esNumerico(linea)) {
move = atoi(linea.c_str());
} else {
cout << "\n\t\t\t\t\tError!, ingrese valor valido\n\n";
move=0;
}
} while (!unTablero.movimientoValido(move));
unTablero.recibirMovimiento(getPieza(), move);
}
Tablero.h
#ifndef TABLERO_H
#define TABLERO_H
#include <iostream>
#include <string> // string, stoi
using namespace std;
class Tablero
{
public:
Tablero();
bool esNumerico(string linea);
bool estaLleno() const;
bool movimientoValido(int move) const;
bool ganador(char ficha) const;
void mostrarTablero() const;
void reiniciarTablero();
void recibirMovimiento(char pieza, int mover);
static const int numero_de_cuadros = 10;
static const char vacio = ' ';
private:
static const int numero_de_combos = 8;
static const int numero_en_combo = 3;
string linea;
static const int combos_ganadores[numero_de_combos] [numero_en_combo];
char m_Cuadrados[numero_de_cuadros];
};
#endif
Tablero.cpp
#include "Tablero.h"
#include <iostream>
using namespace std;
const int Tablero::combos_ganadores[numero_de_combos]
[numero_en_combo] = { {1, 2, 3},{4, 5, 6},{7, 8, 9},{1, 4, 7},{2, 5, 8},{3, 6, 9},{1, 5, 9}, {3, 5, 7} };
Tablero::Tablero()
{
reiniciarTablero();
}
bool Tablero::estaLleno() const
{
bool lleno = true;
int i = 1;
while (lleno && i < numero_de_cuadros)
{
if (m_Cuadrados[i] == vacio)
{
lleno = false;
}
++i;
}
return lleno;
}
bool Tablero::movimientoValido(int mover) const
{
return (mover >= 1 && mover < numero_de_cuadros && m_Cuadrados[mover] ==
vacio);
}
bool Tablero::ganador(char ficha) const
{
bool ganador = false;
int i = 0;
while (!ganador && i < numero_de_combos)
{
int fichasEnCombo = 0;
for (int j = 0; j < numero_en_combo; ++j)
{
if (m_Cuadrados[combos_ganadores[i][j]] == ficha)
{
++fichasEnCombo;
}
}
if (fichasEnCombo == numero_en_combo)
{
ganador = true;
}
++i;
}
return ganador;
}
void Tablero::mostrarTablero() const
{
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| " << m_Cuadrados[1] << " | " << m_Cuadrados[2]; cout << " | " << m_Cuadrados[3]; cout << " | ";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| " << m_Cuadrados[4] << " | " << m_Cuadrados[5]; cout << " | " << m_Cuadrados[6]; cout << " | ";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << "\t\t\t\t\t\t" << "| " << m_Cuadrados[7] << " | " << m_Cuadrados[8]; cout << " | " << m_Cuadrados[9]; cout << " | ";
cout << endl << "\t\t\t\t\t\t" << "-------------";
cout << endl << endl;
}
void Tablero::reiniciarTablero()
{
for (int i=0; i<numero_de_cuadros; ++i)
{
m_Cuadrados[i] = vacio;
}
}
void Tablero::recibirMovimiento(char pieza, int mover)
{
m_Cuadrados[mover] = pieza;
}
bool Tablero::esNumerico(string linea)
{
bool b = true;
int longitud = linea.size();
if (longitud == 0) { // Cuando el usuario pulsa ENTER
b = false;
} else if (longitud == 1 && !isdigit(linea[0])) {
b = false;
} else {
int i;
if (linea[0] == '+' || linea[0] == '-')
i = 1;
else
i = 0;
while (i < longitud) {
if (!isdigit(linea[i])) {
b = false;
break;
}
i++;
}
}
return b;
}