If i use the switch statementthe read part doenst work
int this code i the same "codigo" cant be used twice
so i'm using the mensage
Feedback
"esse codigo ja existe"
pls help me find whats is wrong with this code
Header 1
#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Paciente
{
private:
int codigo, fixo, celular;
string nomePaciente, nomeCovenio;
public:
void setCodigo(int x) {
codigo = x;
}
int getCodigo() {
return codigo;
}
void setFixo(int x) {
fixo = x;
}
void setCelular(int x) {
celular = x;
}
void setNomePaciente(string x) {
nomePaciente = x;
}
void setNomeCovenio(string x) {
nomeCovenio = x;
}
int getFixo() {
return fixo;
}
int getCelular() {
return celular;
}
string getNomeCovenio() {
return nomeCovenio;
}
string getNomePaciente() {
return nomePaciente;
}
};
<i>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <fstream>
#include "Paciente.cpp"
using namespace std;
int main() {
fstream texto1("paciente.txt", ios::in |ios::out| ios::app);
int s;
Paciente p;
string q,z,r;
cout << "1-Cadastramento" << endl << "2-Agendamento" << endl << "3-Alteracao de Paciente" << endl << "4-Vizualizacao de Consultas" << endl;
cin >> s;
switch (s) {
case 1:
int w;
cout << "diga seu codigo" << endl;
cin >> s;
p.setCodigo(s);
cout << "diga seu nome" << endl;
cin >> q;
p.setNomePaciente(q);
cout << "diga seu nome do covenio" << endl;
cin >> q;
p.setNomeCovenio(q);
cout << "diga o seu telefone fixo" << endl;
cin >> w;
p.setFixo(w);
cout << "diga o seu telefone celular" << endl;
cin >> w;
p.setCelular(w);
texto1 << endl << "Paciente " << p.getNomePaciente() << endl;
texto1 << "Covenio " << p.getNomeCovenio() << endl;
texto1 << "Fixo " << p.getFixo() << endl;
texto1 << "Celular " << p.getCelular() << endl;
texto1 << "Codigo " << p.getCodigo() << endl;
texto1.clear();
while (texto1 >> z >> r) {
if (z == "Codigo") {
int x = atoi(r.c_str());
if (x == 12) {
cout << "esse codigo ja existe" << endl;
};
};
};
break;
case 2:
break;
case 3:
break;
case 4:
break;
default:
cout << "Nao eh uma opcao" << endl;
break;
};
texto1.close();
system("pause");
return 0;
}</i>,
An fstream only keeps one file position, shared between read and write.
Each time you switch between reading and writing, you have to do a seek to set the position for the next operation. If you really want to use the current position, you can use the minimum seek of
texto1.seekp(0, ios_base::cur);
which "moves" the file position 0 bytes from the current position. But it's still formally a seek, and you can then either read or write from that position.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So, I am learning about classes in C++, I created two classes, one for a University that contains a list of class Students, i managed to create students, and introduce some values to the classes, but now i want to sort the class students by student number, i tryed using the sort function, but im not succeeding. I will leave my code bellow, please give some good tips and advises, so I can improve my code. thanks
main.css
#include <iostream>
#include "university.h"
#include "students.h"
using namespace std;
int main() {
university univ = university();
return 0;
}
university.h
#pragma once
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
#include "students.h"
using namespace std;
class university
{
private:
list<students> lstudents;
list<students>::iterator itstudents;
public:
university();
void setStudents(list<students> lstudents);
void registerStudent();
void list();
void average();
//void sortstudents();
};
university.cpp
#include "university.h"
using namespace std;
university::university() { //constructor
string resp = "s";
int op;
bool out = true;
cout << "Enter Students:" << endl;
while (resp != "n")
{
this->registerStudent();
cout << "Continue inserting? (s/n)" << endl;
cin >> out;
cin.ignore();
}
while (out)
{
cout << "What you Want to do? (1- List Students 2- Sudent Average 3- Sort Students by Number 4- Leave)" << endl;
cin >> op;
switch (op)
{
case 1:
this->list();
break;
case 2:
this->average();
break;
/*case 3:
this->sortStudents();
break;*/
case 4:
out = false;
break;
};
}
}
void university::setStudents(list<students> lstudents) {
this->lstudents = lstudents;
}
void university::registerStudent()
{
lstudents.push_back(students());
}
void university::list()
{
int sum = 0;
cout << "------------------------- LIST STUDENTS -------------------------------\n\n";
cout << left << setw(11) << "Number"
<< left << setw(30) << "Name"
<< left << setw(30) << "Course"
<< left << setw(10) << "Average";
cout << "\n";
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
(*itstudents).list();
++sum;
}
//cout << "Total de pacientes:" << somatorio << endl;
//somatorio = 0;
}
void university::average()
{
int sum = 0;
double average = 0;
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
average += (*itstudents).getaverage();
++sum;
}
cout << "Average:" << average / sum << endl;
}
//void university::sortstudents() {
// sort(lstudents.begin(), lstudents.end(), &students::compare);
//}
students.h
as you can see the commented code is my attempts on sorting the class student my number
#pragma once
#include <iomanip>
#include <algorithm>
#include <list>
#include "university.h"
using namespace std;
class students {
private:
std::string name;
std::string course;
int number;
double average;
public:
//friend bool operator<(estudantes& left,estudantes& right) { return left.matricula < right.matricula; };
students();
void list();
double getaverage();
int getnumber();
//bool compare(estudantes a, estudantes b);
};
students.cpp
#include "students.h"
students::students() {
cout << "Name: ";
getline(cin, name);
cout << "Course: ";
getline(cin, course);
cout << "Number: ";
cin >> this->number;
cout << "Average: ";
cin >> this->average;
}
void students::list() {
cout << left << setw(11) << number;
cout << left << setw(30) << name;
cout << left << setw(30) << course;
cout << left << setw(10) << average << endl;
}
double students::getaverage() {
return average;
}
int students::getnumber() {
return number;
}
//bool estudantes::compare(student a, student b) {
//
// if (a.number < b.number)
// return 1;
// else
// return 0;
//}
Made it selfcontained and fixed. I'll post and then aexplain as surely people will have closed the question too soon:
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <list>
#include <string>
class students {
private:
std::string name;
std::string course;
int number;
double average;
public:
// friend bool operator<(students& left,students& right) { return
// left.matricula < right.matricula; };
students();
void list();
double getaverage();
int getnumber();
static bool compare(students const& a, students const& b);
};
students::students()
{
std::cout << "Name: "; getline(std::cin, name);
std::cout << "Course: "; getline(std::cin, course);
std::cout << "Number: "; std::cin >> this->number;
std::cout << "Average: "; std::cin >> this->average;
}
void students::list() {
std::cout << std::left << std::setw(11) << number;
std::cout << std::left << std::setw(30) << name;
std::cout << std::left << std::setw(30) << course;
std::cout << std::left << std::setw(10) << average << std::endl;
}
double students::getaverage() {
return average;
}
int students::getnumber() {
return number;
}
bool students::compare(students const& a, students const& b) {
return a.number > b.number;
}
class university {
private:
std::list<students> lstudents;
std::list<students>::iterator itstudents;
public:
university();
void setStudents(std::list<students> lstudents);
void registerStudent();
void list();
void average();
void sortStudents();
};
university::university() // constructor
{
std::string resp = "s";
int op;
bool out = true;
std::cout << "Enter Students:" << std::endl;
while (resp != "n") {
this->registerStudent();
std::cout << "Continue inserting? (s/n)" << std::endl;
std::cin >> out;
std::cin.ignore();
}
while (out) {
std::cout << "What you Want to do? (1- List Students 2- Sudent Average "
"3- Sort Students by Number 4- Leave)"
<< std::endl;
std::cin >> op;
switch (op) {
case 1: this->list(); break;
case 2:
this->average();
break;
case 3: this->sortStudents(); break;
case 4: out = false; break;
};
}
}
void university::setStudents(std::list<students> lstudents) {
this->lstudents = lstudents;
}
void university::registerStudent()
{
lstudents.push_back(students());
}
void university::list()
{
int sum = 0;
std::cout << "------------------------- LIST STUDENTS -------------------------------\n\n";
std::cout << std::left << std::setw(11) << "Number"
<< std::left << std::setw(30) << "Name"
<< std::left << std::setw(30) << "Course"
<< std::left << std::setw(10) << "Average";
std::cout << "\n";
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
(*itstudents).list();
++sum;
}
//std::cout << "Total de pacientes:" << somatorio << std::endl;
//somatorio = 0;
}
void university::average()
{
int sum = 0;
double average = 0;
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
average += (*itstudents).getaverage();
++sum;
}
std::cout << "Average:" << average / sum << std::endl;
}
void university::sortStudents() {
lstudents.sort(&students::compare);
}
int main() {
university univ = university();
return 0;
}
Explanation
There were a number of issues.
students::compare was a non-static member function, meaning it can only be called on an instance of student. To have a 2-argument sort predicate as required, simply making it static can work
The implementation could be much more idiomatic:
bool students::compare(students const& a, students const& b) {
return a.number > b.number;
}
That avoids the C-ism of using 1 as if it were true, and the useless if/else
You used std::sort but it requires random access iterators. std::list doesn't provide that. For that reason std::list::sort exists:
void university::sortStudents() {
lstudents.sort(&students::compare);
}
Among many other style issues:
don't using namespace std;
don't do side-effects in constructors?
error-check IO
avoid division by zero (e.g. in average()
#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().
the program should read from 2 files (author.dat and citation.dat) and save them into a map and set;
first it reads the citationlist without problem, then it seems to properly read the authors and after it went through the whole list (author.dat) a floating point exception arises .. can't quite figure out why
seems to happen in author.cpp inside the constructor for authorlist
author.cpp:
#include <fstream>
#include <iostream>
#include "authors.h"
using namespace std;
AuthorList::AuthorList(char *fileName) {
ifstream s (fileName);
int idTemp;
int nrTemp;
string nameTemp;
try {
while (true){
s >> idTemp >> nrTemp >> nameTemp;
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << "WHILE-LOOP_END" << endl;
}
} catch (EOFException){}
}
author.h:
#ifndef CPP_AUTHORS_H
#define CPP_AUTHORS_H
#include <iostream>
#include <map>
#include <string>
#include "citations.h"
class Author {
public:
Author (int id, int nr, std::string name) :
articleID(id),
authorNR(nr),
authorName(name){}
int getArticleID() const {
return articleID;
}
std::string getAuthorName() const {
return authorName;
}
private:
int articleID;
int authorNR;
std::string authorName;
};
class AuthorList {
public:
AuthorList(char *fileName);
std::pair<std::multimap<int,Author>::const_iterator, std::multimap<int,Author>::const_iterator> findAuthors(int articleID) {
return authors.equal_range(articleID);
}
private:
std::multimap<int,Author> authors;
};
#endif //CPP_AUTHORS_H
programm.cpp:
#include <iostream>
#include <cstdlib>
#include "citations.h"
#include "authors.h"
#include "authorCitation.h"
using namespace std;
int main(int argc, char *argv[]){
CitationList *cl;
AuthorList *al;
//check if argv array has its supposed length
if (argc != 4){
cerr << "usage: programm article.dat citation.dat author.dat";
return EXIT_FAILURE;
}
//inserting citation.dat and author.dat in corresponding lists (article.dat not used)
cl = new CitationList(argv[2]);
al = new AuthorList(argv[3]);
try {
AuthorCitationList *acl;
acl->createAuthorCitationList(al,cl);
acl->printAuthorCitationList2File("authorcitation.dat");
} catch (EOFException){
cerr << "something went wrong while writing to file";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
All files:
https://drive.google.com/file/d/0B734gx5Q_mVAV0xWRG1KX0JuYW8/view?usp=sharing
I am willing to bet that the problem is caused by the following lines of code:
AuthorCitationList *acl;
acl->createAuthorCitationList(al,cl);
You are calling a member function using an uninitialized pointer. I suggest changing the first line to:
AuthorCitationList *acl = new AuthorCitationList;
Add any necessary arguments to the constructor.
While you are at it, change the loop for reading the data also. You have:
while (true){
s >> idTemp >> nrTemp >> nameTemp;
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << "WHILE-LOOP_END" << endl;
}
When you do that, you end up adding data once after the end of line has been reached. Also, you seem to have the last line in the wrong place. It seems to me that it should be outside the while loop.
You can use:
while (true){
s >> idTemp >> nrTemp >> nameTemp;
// Break out of the loop when reading the
// data is not successful.
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
}
cout << "WHILE-LOOP_END" << endl;
You can simplify it further by using:
while (s >> idTemp >> nrTemp >> nameTemp){
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
}
cout << "WHILE-LOOP_END" << endl;
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;
}
I have a problem with my code. I tried to use reference to take my variables from method to main() function and i get this error : "overloaded member function not found". Please Help! :)
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
class Tworzenie_postaci {
public:
Tworzenie_postaci();
string Nazwa_Postaci();
int Wiek_Postaci();
int Staty_Postaci(int Final_Postac_Sila, int Final_Postac_Inteligencja);
int Staty_Postaci();
private:
};
Tworzenie_postaci::Tworzenie_postaci() {
}
string Tworzenie_postaci::Nazwa_Postaci()
{
string wpisz_nazwa;
cout << "Wybierz imie dla swojej postaci:\n";
cin >> wpisz_nazwa;
cout << "Nazwa twojej postaci to:\n" << wpisz_nazwa<< "\n";
return wpisz_nazwa;
}
int Tworzenie_postaci::Wiek_Postaci()
{
int wiek;
cout << "Ile twoja postac ma lat?\n";
cin >> wiek;
cout << "Wiec twoja postac ma " << wiek << " lat\n";
return wiek;
}
void Tworzenie_postaci::Staty_Postaci(int& _Postac_Sila, int& _Postac_Inteligencja) {
int Postac_Sila;
int Postac_Inteligencja;
cout << "Ile twoja postac ma sily? :\n";
cin >> Postac_Sila;
cout << "Twoja postac ma " << Postac_Sila << " sily \n";
cout << "Ile twoja postac ma inteligencji? : \n";
cin >> Postac_Inteligencja;
cout << "Twoja postac ma "<< Postac_Inteligencja << " inteligencji \n";
_Postac_Sila = Postac_Sila;
_Postac_Inteligencja = Postac_Inteligencja;
}
int main()
{
Tworzenie_postaci Postac;
string Final_Imie;
int Final_Wiek;
int Final_Postac_Sila;
int Final_Postac_Inteligencja;
Final_Imie = Postac.Nazwa_Postaci();
Final_Wiek = Postac.Wiek_Postaci();
Postac.Staty_Postaci(Final_Postac_Sila, Final_Postac_Inteligencja);
cout << "\n " << Final_Postac_Sila;
return 0;
}
Sorry for polish names of variables or functions but it is easier for me that way :P
The function is declared as:
int Staty_Postaci(int Final_Postac_Sila,
int Final_Postac_Inteligencja);
It is defined as:
void Tworzenie_postaci::Staty_Postaci(int& _Postac_Sila,
int& _Postac_Inteligencja)
{
...
}
As you can see, the types in the declaration and the definition don't match.
Change one of them to match the other.
Also, the return types must match.