structuring classes for a tic-tac-toe(c++) - c++

I have been learning c++ with 'C++ Programming for
the Absolute Beginner' which have been very useful, whoever when it comes to OOP and splitting the classes into different files it doesn't explain it very well.
This is the code I have, I didn't put everything here, just the problematic stuff. The weird thing is that if I exclude Juego.h and Juego.cpp from the project it lets me build it, but if I include it I get the following errors:
jugador.h(8): error C2146: syntax error : missing ';' before identifier 'c_o'
jugador.h(8): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
jugador.h(9): error C2061: syntax error : identifier 'casilla'
juego.cpp(15): error C2039: 'c_o' : is not a member of 'Jugador'
jugador.h(5) : see declaration of 'Jugador'
Because it only happens with Juego.h in the code I think the problem is that I didn't structure well the header files. I have been able to solve many of the problems searching on google but I can't fix those, I even get syntax errors.
//Jugador.h
#include <string>
using std::string;
class Jugador
{
public:
string p_name;
//casilla is X,O or blankspace, done using enum in Tablero.h( it have to be in a cpp file)
casilla c_o;
Player(string name, casilla marca);
void turno(Tablero* tabla);
};
//Jugador.cpp
#include "Jugador.h"
#inlcude "Tablero.h"
#include <string>
using std::string;
Jugador::Jugador(string nombre,casilla marca): p_name(nombre), c_o(marca) {}
void Jugador::turno(Tablero* tabla)
{
using std::cout;
using std::cin;
int fil;
int col;
do
{
cout << p_name.c_str() <<" en que fila quieres jugar(1-2-3)?\n";
cin >> fil;
cout<<p_name.c_str() <<" en que columna quieres jugar(1-2-3)?\n";
cin >> col;
}while(tabla->tab[fil-1][col-1]==vacia);
tabla->tab[fil-1][col-1]=c_o;
}
//Juego.h
class Jugador;
class Tablero;
class Juego
{
public:
Juego(void);
bool ganador(Jugador* player, Tablero* tabla);
bool fin(Tablero* tabla);
};
//Juego.cpp
#include "Juego.h"
#include "Jugador.h"
#include "Tablero.h"
Juego::Juego() {}
bool Juego::ganador(Jugador* player, Tablero* tabla)
{
using std::cout;
using std::cin;
casilla marca_jug = player->c_o;
bool winner = false;
//...
// if-else structure which set winner to true if the conditons to win are achived
if (winner)
cout<<player->p_name.c_str()<<" ha ganado!!!!\n";
return winner;
}
//if there isnt any blank square, ends the game
bool Juego::fin(Tablero* tabla)
{
bool fin_juego=false;
for(int fil=0; fil<3; fil++)
{
for(int col=0; col<3; col++)
{
if(tabla->tab[fil][col]==vacia)
fin_juego=true;
}
}
return fin_juego;
}
As I said it isn't the whole code, I wasnt to have more things that needed just to make everything clearer I'm gonna add tablero.h
Here is were casilla is defined. Casilla is a 2D array:
//Tablero.h
#include <iostream>
#include <string>
enum casilla {vacia,X,O};
class Tablero
{
public:
casilla tab[3][3];
Tablero(void);
void draw(void);
};
//Tablero.cpp
#include "Tablero.h"
Tablero::Tablero(void)
{
using std::cout;
casilla tab[3][3];
for(int f=0;f<3;f++)
{
for (int c= 0;c<3;c++)
{
tab[f][c]=vacia;
}
}
}
void Tablero::draw(void)
{
using std::cout;
using std::string;
for(int f=0;f<3;f++)
{
for (int c= 0;c<3;c++)
{
string s;
if (c!=2)
{
switch (tab[f][c])
{
case vacia: s=" "; break;
case X: s="X"; break;
case O: s="O";break;
}
cout << s.c_str() <<" | ";
}
else
{
switch (tab[f][c])
{
case vacia: s=" "; break;
case X: s="X"; break;
case O: s="O"; break;
}
cout << s.c_str() <<"\n";
}
}
}
}

Let us look at the first error.
//Jugador.h
#include <string>
using std::string;
class Jugador
{
public:
string p_name;
//casilla is X,O or blankspace, done using enum in Tablero.h( it have to be in a cpp file)
casilla c_o;
At this moment, the compiler does not know what a casilla is. Perhaps it is in some other file which has to be included, too, before any use of it:
//Jugador.h
#include <string>
#include <where-casilla-is-from>
using std::string;
...

Related

Program flash back in the begin when I use the "vector" or other dynamic array

Program flash back in the begin when I use the "vector" or other dynamic array.
I use the vscode with gcc 6.3.0 and gdb 8.2.
I can't debug or break point because the exe crash in the begin without any Error.
I try to change the gcc/gdb to version higher or lower,it's not effect.
But it works in vs2017,But I want it works in gdb,too.
#include <conio.h>
#include <iostream>
#include <vector>
using namespace std;
class Something{
int id;
};
int main() {
int num;
cin >> num;
vector<Something> something;
//Something *somethings = new Something[num];
for (;;) {
if (_kbhit()) {
if (_getch() == 27) {
break;
}
}
}
return 0;
}

Enum Array as parameter c++

I am new to c++ and I want to include an array of Enum values, and I am getting a syntax error in Microsoft Visual Studio. I am not sure why this is the case any help much appreciated. The error number is C2061 and it states "syntax error: identifier 'VerboseBinary'. Here is the code:
Header file verbose_binary.h
#pragma once
#include <bitset>
enum class VerboseBinary : int {
One,
Two,
Four,
Eight,
Sixteen,
Null,
};
void convert(std::bitset<5> bs, VerboseBinary aVB[6]);
verbose_binary.cpp
#include "verbose_binary.h"
#include "stdafx.h"
#include <bitset>
#include <string>
#include <iostream>
void convert(std::bitset<5> bs, VerboseBinary aVB[6]) {
VerboseBinary VBArray[6] = {
VerboseBinary:: One,
VerboseBinary:: Two,
VerboseBinary:: Four,
VerboseBinary:: Eight,
VerboseBinary:: Sixteen,
VerboseBinary:: Null
};
for (int i = 0; i < 5; i++) {
if (bs.test(i)) {
aVB[i] = VBArray[i];
}
else {
aVB[i] = VerboseBinary::Null;
}
}
aVB[5] = VerboseBinary::Null;
}
Main
#include "stdafx.h"
#include <iostream>
#include <iostream>
#include <bitset>
#include "verbose_binary.h"
int main() {
int a, b;
std::bitset<5> aBs, bBs;
std::cout << "Enter two numbers between 0-31:" << std::endl;
std::cin >> a >> b;
if (a<0 || a>31) return -1;
if (b<0 || b>31) return -2;
aBs = static_cast<std::bitset<5>>(a);
bBs = static_cast<std::bitset<5>>(b);
// std::cout << aBs << " " << bBs << std::endl;
VerboseBinary aVB[6];
VerboseBinary bVB[6];
convert(aBs, aVB);
convert(bBs, bVB);
return 0;
}
Lol, so it looks like one of these issues was resposible for the error:
What version of Visual Studio are you using? enum with class became available with VS 2012.
Also, there is a stray comma at the end of your enum's definition.
Also, stdafx.h should appear before any other includes in verbose_binary.cpp.
Main has a benign double-inclusion for <iostream>

c++ method parameters giving unexpected output

Main class code:
#include <iostream>
#include "Chair.h"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
Chair c1;
c1.chairType("Olivia",4,32,true); // not working
Chair c2;
c1.chairType("Stephano",8,8,false);
return 0;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Header class code:
#ifndef CHAIR_H_INCLUDED
#define CHAIR_H_INCLUDED
#include <iostream>
using namespace std;
class Chair
{
private:
int legCount;
int height;
bool cushioned;
string name;
public:
void chairType(string newName, int newLegCount, int newHeight, bool cush);
};
#endif // CHAIR_H_INCLUDED
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Chair.cpp class:
#include <iostream>
#include "Chair.h"
using namespace std;
void Chair::chairType(string newName, int newLegCount, int newHeight, bool cush)
{
name=newName;
legCount=newLegCount;
newHeight=newHeight;
cushioned=cush;
cout<<"I'm a chair, the following are my specs: "<<endl;
cout<<"Model: "<<name<<endl;
cout<<"Num of Legs: "<<legCount<<endl;
cout<<"Height: "<<height<<endl;
cout<<"Cushioned? : "<<cush<<endl;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Output for the four variables fed into the method is as expected, apart from the third variable (second int) which is printing as being 2752192 regardless of what I feed to it, and for both objects c1 and c2.
I'm new to C++. I've been practising some object class questions trying to familiarise myself with the syntax. I vaguely understand pointers can cause reference addresses to print on occasion. However, this 7 digit number doesn't appear to be in address format. I've done some searches and can't see a similar question. If there is one, I would appreciate direction to it. I don't wish to break the terms of posting here on the site. Thank you in advance for your assistance.
newHeight=newHeight;
should be replaced with
height=newHeight;
but better you should initialize object in constructor, rather than separate method:
class Chair
{
private:
int legCount;
int height;
bool cushioned;
string name;
public:
Chair( const string &newName, int newLegCount, int newHeight, bool cush) :
legCount( newLegCount ),
height( newHeight ),
cushioned( cush ),
name( newName )
{
}
...
};
int main()
{
cout << "Hello world!" << endl;
Chair c1("Olivia",4,32,true); // works now
Chair c2("Stephano",8,8,false);
return 0;
}
this way you cannot have instance of your class uninitialized and your mistake also would be detected by compiler.
Here is the mistake in your implementation Chair.cpp:
newHeight=newHeight;
This is the correct:
height = newHeight;
The long number you get is the uninitialized value of member variable height in your Chair object.

need help on #include doesn't seem to be working

So I have a class called HPStack and I have to include it in my main class etc. However I get a "In File included from" error, what could be causing this?
Also my string objects also have errors I have have no idea why, the error is: "Unable to identifier string".
I'm new the C++ so any help would be appreciated, thanks in advance.
The error I am getting (I think) are these:
error: expected unqualified-id before "namespace"
error: expected `,' or `;' before "namespace"
error: expected namespace-name before ';' token
error: `<type error>' is not a namespace
Im not sure what I am missing but that isn't telling me much.
Here is my code: The class.h file.
#ifndef HPSTACK_H
#define HPSTACK_H
class HPStack {
public:
HPStack();
void push(double);
double pop();
double peek();
private:
double register_[4];
}
#endif
The class.cpp file.
#include "HPStack.h"
#include <cstdlib>
HPStack::HPStack() : register_{}{
}
double HPStack::push(double x) {
for (int i = 2; i >= 0; i--) {
if (isdigit(register_[i])) {
register_[i] = register_[i + 1];
}
register_[0] = x;
}
}
double HPStack::pop() {
return register_[0];
for (int i = 0; i < 3; i++) {
register_[i] = register_[i + 1];
}
}
double HPStack::peek() {
return register_[0];
}
And my main file:
#include "HPStack.h"
#include <cstdlib>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
HPStack stack;
string line;
while (getline(cin, line)) {
stringstream expression(line);
string token;
while (expression >> token) {
if (isdigit(token[0])) {
stack.push(atof(token.data()));
} else if (token == "+") {
double x = stack.pop();
double y = stack.pop();
double z = (y + x);
stack.push(z);
}
}
cout << stack.peek();
}
The error is, I'm guessing, because of this line:
double register_[4] = {};
You can not initialize class members when declaring them.
If your compiler is new enough to support C++11 features, you can use an initializer list with the constructor:
HPStack::HPStack()
: register_{}
{
}
Otherwise you have to initialize the array manually in the constructor.
And as I noted in a comment, using register_ - 2 makes no sense as it returns a pointer so the index variable i will be way beyond the end of the array.
And using register_ - 1 as the condition in the pop loop makes even less sense, as it will always be non-zero and therefore always true and the loop will loop forever.
You're missing the ; at the end of the class definition:
class HPStack {
...
}; // <== This semicolon is required

scope error message

Hey guys, just learning about composition of classes and ran into this error.
Gradebook.h
#ifndef GRADEBOOK_h
#define GRADEBOOK_h
#include "StudentRec.h"
#include <iostream>
#include <string>
class GradeBook
{
public:
GradeBook();
GradeBook(string initLastName, int studGrades);
void AddStudent(string initLastName, int studGrades);
void ShowStudents();
void UserInterface();
private:
static const int numStudents=20;
StudentRec student[numStudents];
static int studentCounter;
static int gradeCounter;
};
#endif
Gradebook.cpp
#include "Gradebook.h"
#include "StudentRec.h"
#include <iostream>
#include <string>
using namespace std;
GradeBook::GradeBook()
{}
GradeBook::GradeBook(string initLastName, int studGrades)
{}
void GradeBook::AddStudent(string initLastName, int studGrades)
{
gradeCounter++; //Increments variable responsible for tracking # of grades per student
StudentRec newStudent(initLastName, studGrades); //creates new student object
student[studentCounter]=newStudent; //Assigns new student object to array
studentCounter++; //Increments variable responsible for tracking # of students
}
void GradeBook::ShowStudents()
{
for(int i=0;i<studentCounter; i++){ //Displays information for each student instance
cout<<student[i].GetLastName()<<' ';
for(int j=0; j<gradeCounter; j++)
cout<<student[i].GetGrades(j)<<' ';
cout<<endl;
}
}
void GradeBook::UserInterface()
{
char choice=' ';
string studLastName;
int studGrade;
cout<<"Welcome to GradeBook, this program stores students"
<<" grades by last name. To ADD a student press the 'A'"
<<" key. To LIST all students, press the 'L' key. To "
<<" QUIT, press the 'Q' key."<<endl<<endl;
cin>>choice;
choice=toupper(choice);
while(choice!='Q')
{
if(choice='A'){
cout<<"To add a student, please enter their last name"
<<" followed by a space and a non-negative grade"
<<" Ex. McClure 96";
cin>>studLastName>>studGrade;
AddStudent(studLastName, studGrade);
}
else if(choice='L'){
cout<<"This is a list of all students in GradeBook"
<<endl<<endl;
ShowStudents(); //Displays all StudentRec objects
}
else if(choice!='Q')
cout<<"Please enter another letter"<<endl;
cout<<"To ADD a student press the 'A' key. To LIST all students, press the 'L' key. To "
<<" QUIT, press the 'Q' key."<<endl<<endl;
}
}
Main.cpp
#include <iostream>
#include <string>
#include "StudentRec.h"
#include "Gradebook.h"
using namespace std;
int main()
{
GradeBook gradeBook;
UserInterface();
return 0;
}
StudentRec.cpp
#include <iostream>
#include <string>
#include "StudentRec.h"
using namespace std;
StudentRec::StudentRec()
{
lastName=" ";
for(int i=0;i<numGrades; i++)
grades[i]=0;
}
StudentRec::StudentRec(string initLastName, int studGrade)
{
static int gradeCounter=0;
lastName=initLastName;
grades[gradeCounter]=studGrade;
}
string StudentRec::GetLastName()
{
return lastName;
}
int StudentRec::GetGrades(int gradeNum)
{
return grades[gradeNum];
}
void StudentRec::AddGrades(int studGrade)
{
gradeCounter++;
if(gradeCounter<=numGrades)
grades[gradeCounter]=studGrade;
else
cout<<"Too many grades for this student";
}
StudentRec.h
#ifndef STUDENTREC_h
#define STUDENTREC_h
#include <iostream>
#include <string>
using namespace std;
class StudentRec
{
public:
StudentRec();
StudentRec(string initLastName, int studGrade);
string GetLastName();
int GetGrades(int gradeNum);
void AddGrades(int studGrade);
private:
static const int numGrades=10;
static int gradeCounter;
string lastName;
int grades[numGrades];
};
#endif
In the Main.cpp file, I get an error I can't find the solution for. It reads
error: "UserInterface" was not declared in this scope. I got this error while compiling in XCode
I got error C3861: 'UserInterface': identifier not found
Obviously i've tried it in two IDEs, I also have the StudentRec.cpp and .h, but not sure you need them. Thanks in advance for the help
It appears that UserInterface() is actually a member function of GradeBook, correct?
If so, you need to add a declaration for the member function in the GradeBook class declaration:
class GradeBook
{
public:
GradeBook();
GradeBook(string initLastName, int studGrades);
void AddStudent(string initLastName, int studGrades);
void ShowStudents();
void UserInterface(); // Added
// ...
private:
// ...
};
This way, the compiler will "know" that the UserInterface() function exists as a member function. You then provided the definition in void GradeBook::UserInterface() in your .cpp file.
Then you need to call it on a GradeBook instance, like the gradeBook variable in your main() function:
int main()
{
GradeBook gradeBook;
// This calls the member function UserInterface() on the gradeBook variable.
gradeBook.UserInterface();
// This calls the global UserInterface(), which doesn't exist.
// UserInterface();
return 0;
}
UserInterface() is a method of GradeBook. The call probably needs to be:
gradeBook.UserInterface();