array of strings inside the object - c++

I've got a problem with creating an array of strings inside the object. I don't know how to patch it around so I'm asking for help. Here lies the problem:
main.h:
#pragma once
#include <iostream>
#include <conio.h>
#include <string>
class tab2D {
protected:
int width;
int height;
string **sTab;
int **iTab;
public:
tab2D();
tab2D(int x, int y, char c);
~tab2D();
tab2D(tab2D&t);
};
class chess: public tab2D {
public:
chess(int x, int y);
~chess();
chess(chess&c);
void init();
bool ifMove();
void show();
};
class matrix: public tab2D {
public:
matrix(int x, int y);
~matrix();
matrix(matrix&m);
};
The compiler says: syntax error : missing ';' before '*' about the line
string **sTab;
I assume that I can't make the dynamic array of strings and it makes further problems with processing this array.. Can you help me? :)
*UPDATE 1*Thanks, I forgot to add line
using namespace std;
Now it works, but I've got another problem.
#include "main.h"
using namespace std;
////// Konstruktor, konstruktor kopiujący oraz destruktor //////
chess::chess(int x = 8, int y = 8) : tab2D(x, y, 'c') {
init();
};
chess::chess(chess&c) {
chess(c.width, c.height);
};
chess::~chess() {
};
////// Metody //////
////// Uzupełnianie kolorów pól oraz rozstawianie figur i pionków //////
void chess::init() {
/// kolory pól: 0 - biały, 1 - czarny///
int last = 0;
for(int i = 0; i < this->height; ++i) {
for(int j=0; j < this->width; ++j) {
if(last = 0) {
this->sTab[i][j] = "1";
last = 1;
}
else if(last = 1) {
this->sTab[i][j] = "0";
last = 0;
}
}
if(last = 0)
last = 1;
else if(last = 1)
last = 0;
};
/// rozstawienie pionków ///
for(int i = 0; i < this->width; ++i) {
sTab[1][i] = sTab[1][i] + "0";
sTab[6][i] = sTab[6][i] + "a";
};
};
////// Wyświetlenie szachownicy //////
void chess::show() {
for(int i = 0; i < (this->height + 1); ++i) {
for(int j=0; j < (this->width + 1); ++j) {
if(i == 0 && j == 0)
cout << " ";
else if (i != 0 && j == 0) {
switch (i) {
case 1:
cout << "A ";
break;
case 2:
cout << "B ";
break;
case 3:
cout << "C ";
break;
case 4:
cout << "D ";
break;
case 5:
cout << "E ";
break;
case 6:
cout << "F ";
break;
case 7:
cout << "G ";
break;
case 8:
cout << "H ";
break;
default:
break;
}
}
else if (i == 0 && j != 0) {
cout << j << " ";
}
else {
cout << this->sTab[i-1][j-1] << " ";
}
}
cout << endl;
};
};
When I run the program, there is a breakpoint in the line
this->sTab[i][j] = "0";
I assume there is something wrong with making the array of strings but I don't understand why exactly there is a breakpoint and can't debug it.
UPDATE 2
Here is the code for tab.cpp:
#include "main.h"
using namespace std;
////// Konstruktor domyślny, konstruktor, konstruktor kopiujący oraz destruktor //////
tab2D::tab2D() {
};
tab2D::tab2D(int x, int y, char c) {
this->width = x;
this->height = y;
if (c == 'm') {
this->iTab = new int*[this->width];
for(int i=0;i<this->height;++i)
this->iTab[i] = new int[this->width];
}
else if (c == 'c') {
this->sTab = new string*[this->width];
for(int i=0;i<this->height;++i)
this->sTab[i] = new string[this->width];
}
else {
}
};
tab2D::tab2D(tab2D&t) {
tab2D(t.width, t.height, 't');
};
tab2D::~tab2D() {
for(int i=0;i<height;++i)
delete [] iTab[i];
delete [] iTab;
for(int i=0;i<height;++i)
delete [] sTab[i];
delete [] sTab;
};

You need to qualify names from the standard library:
std::string **sTab;
^^^^^
If you're doing what I think you're doing and allocating things with new, then you should consider using std::vector to deal with the quagmire of memory management issues you're about to encounter. If you really want to juggle pointers yourself for some reason, don't forget the Rule of Three.
UPDATE Your new problem might be because the copy constructor is horribly broken:
chess::chess(chess&c) {
chess(c.width, c.height);
};
This creates and destroys a temporary object, but doesn't initialise the object being constructed, leaving it in an invalid state. You probably don't want to declare a copy-constructor at all, as long as the base class is correctly copyable. If you did need one, it should should be more like:
chess::chess(chess const & c) : // 'const' so constant objects can be copied
tab2D(c) // copy the base-class subobject
{
// do whatever else needs doing
}
Alternatively, the new problem might be due to errors in the tab2D constuctors which you haven't shown us. The best way to track it down is to step through the program with a debugger, checking that everything is correctly initialised before use.
UPDATE Probably, the runtime error is caused by allocating the wrong number of pointers. You want
iTab = new int*[height]; // Not width
and likewise for sTab.

Related

coordinating objects on the screen

So I want to display an object with certain coordinates on the screen and make it able to move. If for example "u" is pressed it goes up and etc. So I tried using variables X and Y (initialized to 0) and after a "clear screen" deploying the object with a for loop. So check this out:
#include <iostream>
#include <conio.h>
#include <cstdlib>
#include <vector>
#include <iomanip>
using namespace std;
char input;
char player = 1;
char keyup = 0x48, keydown = 0x50, keyright = 0x4d, keyleft = 0x4b;
int x = 0, y = 0;
void position()
{
for (int start = 0; start <= y; start++)
{
cout << "\n";
}
for (int start = 0; start <= x; start++)
{
cout << " ";
}
cout << player;
}
void moveup()
{
x - 1;
system("cls");
position();
}
void movedown()
{
y + 1;
system("cls");
position();
}
void moveright()
{
x + 1;
system("cls");
position();
}
void moveleft()
{
y - 1;
system("cls");
position();
}
int main()
{
while (1)
{
position();
cin >> input;
if (input == keyup) moveup();
if (input == keydown) movedown();
if (input == keyright) moveright();
if (input == keyleft) moveleft();
system("cls");
}
}
So when I run it it just shows me the cube for ASCII key = 1; And no matter what I press it just blinks showing me the 'player' on the same position.
Can you guys tell me what is the PROBLEM?
At first, I recomment using character literals instead of numerical values:
char const keyup = 'u';
// ^ they are constants, aren't they???
0 is not a printable character, so using it as symbol won't print anything on the screen... You might use e. g. '+' instead.
Then you are repeating pretty much code within your functions. What you actually need is just one printing function; something like:
void update()
{
system("cls");
for(int i = 0; i < y; ++i)
std::cout << '\n'; // navigate to appropriate line
for(int i = 0; i < x; ++i)
std::cout << ' '; // navigate to column
std::cout << symbol << std::endl; // endl flashes buffer, too
}
You can use this to print the the symbol to current position (x/y). On input you just need to modify the coordinates (I personally recommend a switch statement instead of the if/else chain):
std::cin >> input;
switch(input)
{
case keyup: // NEEDS to be a constant to be used that way!
--y;
break;
case keydown:
++y;
break;
case keyleft:
--x;
break;
case keyright:
++x;
break;
default: // catch invalid user input
// if you have, appropriate error handling – or just ignore
break;
}
An empty default could be left out – it's a good habit, though, always to catch the invalid cases.
Finally: The second clearing of the screen (after your if/else chain) would empty the screen again before user might have seen anything. Just leave it out. All combined:
for(;;)
{
update(); // first screen update and returning here in every loop
std::cin >> input;
switch(input)
{
// ...
case ExitKey: // recommend to add it!
// the only disadvantage of switch: cannot use 'break' to exit loop!
goto LOOP_END;
default:
break;
}
}
LOOP_END:
// clean up application
return 0; // exit main...
One thing I yet omitted above, but very important: range checks! Before incrementing or decrementing one of the coordinates, you need to check if you can at all:
if(x > 0)
--x;
Or a variant I personally like:
y += y < SCREEN_HEIGHT; // needs to be defined appropriately...
About screen size: this might be of interest...
So the improved code would look like this:
#include <iostream>
#include <conio.h>
#include <cstdlib>
#include <vector>
#include <iomanip>
using namespace std;
char input;
char player = 1;
const char keyup = 'u', keydown = 'd', keyright = 'r', keyleft = 'l', Exitkey = 'k';
int x = 0, y = 0;
void space()
{
for (int start = 0; start < 7; start++)
{
cout << "\n";
}
}
void update()
{
system("cls");
for (int i = 0; i < y; ++i)
cout << '\n';
for (int i = 0; i < x; ++i)
cout << ' ';
cout << player << endl;
}
void inputfunc()
{
cin >> input;
switch (input)
{
case keyup:
if (y = 0)
{
y = 0;
}
else --y;
goto endloop;
case keydown:
++y;
goto endloop;
case keyleft:
if (x = 0)
{
x = 0;
}
else --x;
goto endloop;
case keyright:
++x;
goto endloop;
case Exitkey:
goto endloop;
default:
break;
}
endloop:;
}
int main()
{
for (;;)
{
update();
space();
inputfunc();
}
}
And one more thing: I do not know how to make it automatically after entering ONE character go on. I need to enter as many characters as I want and then press ENTER to deploy the player.How can I do that Scheff?

Getter and Segmentation Fault

I need a bit of help on my program:
#include <iostream>
#include<conio.h>
using namespace std;
class Position {
public :
int line;
int column;
Position(int,int);
Position();
};
Position::Position(int n, int m) : line{n},column{m}{}
class Board {
private :
int** tab;
int nbline;
int nbcolumn;
public :
Board(int, int);
void setValue(Position&, int);
int getValue(Position&);
int getNbline();
int getNbcolumn();
};
class Play {
private :
// Play m_instance;
void moves(Board, Position&); // quand le joueur joue
// void moves(Board, Position); // quand l'IA joue. Mettre une énum pour direction,
bool wincondition(Board);
Play& operator=(const Play&);
public :
// static Play& Instance();
};
Board::Board(int m, int n) : tab{new int*[m]}, nbline{m}, nbcolumn{n}{
int x(0);
for (int i = 0; i < m; ++i){
tab[i] = new int[n];
for(int j = 0; j < n; ++j) {
tab[i][j] = x; x++;}}
}
void Board::setValue(Position& p, int value) { tab[p.line][p.column] = value; }
int Board::getValue(Position& p) { return tab[p.line][p.column]; }
int Board::getNbline() { return nbline; }
int Board::getNbcolumn() { return nbcolumn; }
void Play::moves(Board tab, Position& blank) {
/* int c = getch() ;
Position tmp;
if(c==0 || c==224) {c = getch();
switch(c){
case 75 : //left
if(blank.column-1>=0) {
tmp.column = blank.column;
tmp.line = blank.line;
tab.setValue(blank,tab.getValue(tmp));
blank.column++;
tab.setValue(blank, 0);
}
break;
case 72 : // haut
if(blank.line+1<=0) {
tmp.column = blank.column+1;
tmp.line = blank.line;
tab.setValue(blank,tab.getValue(tmp));
blank.column++;
tab.setValue(blank, 0);
}
break;
case 77 ://droit
if(blank.column+1<=tab.getNbcolumn()) {
tmp.column = blank.column;
tmp.line = blank.line;
tab.setValue(blank,tab.getValue(tmp));
blank.column--;
tab.setValue(blank, 0);
}
break;
case 80 : //bas
if(blank.line+1<=tab.getNbline()) {
tmp.column = blank.column+1;
tmp.line = blank.line;
tab.setValue(blank,tab.getValue(tmp));
blank.column++;
tab.setValue(blank, 0);
}
break;
default : cout << "\n ERROR " << endl; break; // erreur
}
}*/
}
int main()
{
int lines, columns;
cout << "Enter number of lines" << endl;
cin >> lines;
cout << "Enter number of columns" << endl;
cin >> columns;
Board tab(lines,columns);
Position pos(lines,columns);
Position& p = pos;
for (int i = 0; i<lines;i++)
{
for(int j = 0; j<columns;j++)
{
cout << tab.getValue(p) << " ";
if (i == lines) { cout << endl;}
}
}
return 0;
}
When I call getValue at line 139, I get a segmentation fault. Get value is defined at line 57. When executing getValue, both p.line and p.column got the right values caught at the beginning of main function.
The program got no errors, only 2 warnings because I don't use Play::moves arguments (because currently between /* */, waiting for tests). I use Code::Blocks with -Wall -Wextra -pedantic -std=c++11.
I really see no reason for a segmentation fault. Did I miss something?
You are calling get with a position that is set to the size of your board. Since arrays are 0 index based the size of your array is actually one past the end of the array.
const int size = 100
int arr[size]; //0, 1, 2, ... 98, 99
arr[size]; // fail arr is 0-99 and size is 100

Really frustrating debug Error with C++

So I am trying to make a pretty basic TicTacToe in C++, and while I have no apparent syntax errors, I am having a lot of Debug errors of : "Unhandled exception at 0x0100142D in Cobra.exe: 0xC0000005: Access violation reading location 0xCCCCC359"
I feel like it is an obvious Error that I am just not processing but it;s definitely starting to grate my nerves. I'll label where the access error is... Right now it;s in my checkwin method but I feel like there is definitely more than one..
In my header I use a private char** board and a private int player.
#include "TicTacToe.h"
#include <iostream>
using namespace std;
int main()
{
int rowChosen,
colChosen;
TicTacToe newGame;
while(newGame.checkWin()==' ' && !newGame.fullBoard())
{
newGame.displayBoard();
do
{
cout << "Player " << newGame.getPlayer() << " choose a row and column.";
cin >> rowChosen >> colChosen;
newGame.setGame(rowChosen,colChosen);
}while(newGame.setGame(rowChosen,colChosen)==false);
newGame.makeMove(rowChosen, colChosen, newGame.getPlayer());
newGame.switchPlayer();
}
newGame.displayBoard();
if(newGame.checkWin()!=' ')
cout << "Player " << newGame.returnWinner() << " wins!";
else if(newGame.fullBoard()==true)
cout << "Cat's Game: This is a Draw!";
return 0;
}
TicTacToe::TicTacToe()
{
player = 1;
char blank = ' ';
for(int row=0;row<3;row++)
for(int col=0;col<3;col++)
board[row][col] = ' ';
}
void TicTacToe::setPlayer(int play)
{
player = play;
}
int TicTacToe::getPlayer()
{
return player;
}
void TicTacToe::switchPlayer()
{
if (player==1)
player++;
else
player--;
}
bool TicTacToe::setGame(int row, int col) //input validation
{
if (row >= 3 || row < 0)
return false;
if (col >= 3 || col < 0)
return false;
if (board[row][col] != ' ')
return false;
return true;
}
char TicTacToe::getBoard(int row, int col)
{
return board[row][col];
}
bool TicTacToe::fullBoard()
{
bool full = true;
for(int row=0;row<3;row++)
for(int col=0;col<3;col++)
{
if(board[row][col]==' ')
{
full=false;
break;
}
}
return full;
}
void TicTacToe::makeMove(int r, int c, int player)
{
char ch;
if (player==1)
ch = 'X';
else
ch = 'O';
board[r][c] = ch;
}
char TicTacToe::checkWin()
{
char b = ' ';
for(int i=0; i<3; i++) //horizontal
{
if((board[i][1]==board[i][0]) && (board[i][1]==board[i][2])) //THIS IS ERROR
{
b=board[i][1];
}
}
for(int j=0; j<3; j++) //vertical
{
if( (board[1][j]==board[0][j]) && (board[1][j]==board[2][j]) )
b=board[1][j];
}
if((board[0][0]==board[1][1] && board[1][1]==board[2][2]) ||
(board[2][0]==board[1][1] && board[1][1]==board[0][2]))
b= board[1][1];
return b;
}
void TicTacToe::displayBoard()
{
for(int row=0;row<3;row++)
{
cout << "|-----|";
for(int col=0;col<3;col++)
{
if(board[row][col]==' ')
cout << "| ";
else
cout << "|" << board [row][col];
}
cout << "|" << endl;
cout << "|-----|";
}
}
int TicTacToe::returnWinner()
{
int winner = 0;
if(checkWin()=='X')
winner = 1;
else if(checkWin()=='O')
winner = 2;
return winner;
}
This is my header TicTacToe.h
class TicTacToe
{
private:
char board[3][3]; //there we go
int player;
public:
TicTacToe();
void setPlayer(int);
int getPlayer();
void switchPlayer();
bool setGame(int,int);
char getBoard(int,int);
bool fullBoard();
void makeMove(int,int,int);
char checkWin();
void displayBoard();
int returnWinner();
};
Assuming you've included all the code, you're missing something essential: the declaration of the class TicTacToe. Of course, there's a TicTacToe.h, so it could be (probably is) hiding in there. That would help.
That all said, I think Mat has it right -- you declare a local named board inside the ctor and initialize it. But that goes out of scope as soon as the ctor is finished, which means all that initialization disappears into the aether.. Assuming you define board in your class, then simply removing that char declaration might be all you need.
Now, here's general advice: if you get an access violation exception, it usually means that you have made a mistake about the scope of something you're referring to. Since the exception happens at a point where you're using board, the slice of the program containing the identified board is the place to look.

Crashing when objects are deleted

It's crashing at the very end of the main() function where it needs to delete the starters objects. The error message that pops up when I run the program says: Debug assertion failed! Expression: _BLOCK_IS_VALID(pHead->nBlockUse). How do i fix it from crashing when deleting the starters objects?
#include <iostream>
#include <fstream>
#include "olympic.h"
using namespace std;
ofstream csis;
int main() {
const int lanes = 4;
Ranker rank(lanes);
csis.open("csis.txt");
// First make a list of names and lane assignments.
Competitor* starters[lanes];
starters[0] = new Competitor("EmmyLou Harris", 1);
starters[1] = new Competitor("Nanci Griffith", 2);
starters[2] = new Competitor("Bonnie Raitt", 3);
starters[3] = new Competitor("Joni Mitchell", 4);
// The race is run; now assign a time to each person.
starters[0]->setTime((float)12.0);
starters[1]->setTime((float)12.8);
starters[2]->setTime((float)11.0);
starters[3]->setTime((float)10.3);
// Put everyone into the ranker.
for (int i = 0; i < lanes; i++)
rank.addList(starters[i]);
// Now print out the list to make sure its right.
cout << "Competitors by lane are:" << endl;
csis << "Competitors by lane are:" << endl;
for (int i = 1; i <= lanes; i++)
rank.getLane(i)->print();
// Finally, show how they finished.
cout << "Rankings by finish are:" << endl;
csis << "Rankings by finish are:" << endl;
for (int i = 1; i <= lanes; i++)
rank.getFinish(i)->print();
for (int i = 0; i < lanes; i++)
delete starters[i];
csis.close();
}
ranker.cpp:
#include "ranker.h"
#include "competitor.h"
#include <stdlib.h>
Ranker::Ranker(int lanes) {
athlete = new Competitor*[lanes];
numAthletes = 0;
maxAthletes = lanes;
}
int Ranker::addList(Competitor* starter) {
if (numAthletes < maxAthletes && starter != NULL) {
athlete[numAthletes] = starter;
numAthletes++;
return numAthletes;
}
else
return 0;
}
Competitor* Ranker::getLane(int lane) {
for (int i = 0; i < numAthletes; i++) {
if (athlete[i]->getLane() == lane) {
return athlete[i];
}
}
return NULL;
}
Competitor* Ranker::getFinish(int position) {
switch(position) {
case 1:
return athlete[3];
break;
case 2:
return athlete[2];
break;
case 3:
return athlete[1];
break;
case 4:
return athlete[0];
break;
}
return NULL;
}
int Ranker::getFilled() {
return numAthletes;
}
Ranker::~Ranker() {
delete [] athlete;
}
competitor.h:
#ifndef _COMPETITOR_H
#define _COMPETITOR_H
class Competitor {
private:
char* name;
int lane;
double time;
public:
Competitor(char* inputName, int inputLane);
Competitor();
void setTime(double inputTime);
char* getName();
int Competitor::getLane();
double getTime();
void print();
~Competitor();
};
#endif
competitor.cpp:
#include "competitor.h"
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
Competitor::Competitor(char* inputName, int inputLane) {
name = inputName;
lane = inputLane;
}
Competitor::Competitor() {
name = 0;
lane = 0;
time = 0;
}
void Competitor::setTime(double inputTime) {
time = inputTime;
}
char* Competitor::getName() {
return name;
}
int Competitor::getLane() {
return lane;
}
double Competitor::getTime() {
return time;
}
void Competitor::print() {
cout << setw(20) << name << setw(20) << lane << setw(20) << setprecision(4) << time << endl;
}
Competitor::~Competitor() {
delete [] name;
}
Call stack:
before crash: http://i.imgur.com/d4sKbKV.png
after crash: http://i.imgur.com/C5cXth9.png
After you've added Competitor class, it seems the problem is that you delete its name in Competitor's destructor. But you assign it from string literal which can't really be deleted. I'm sure the stack trace leading to assertion will prove that.
One way of solving the problem would be using std::string to store the name.
Problem is when deleting the char* value on destructor, which is assigned with const char instead new char. So i have slightly changed the constructor to copy the const char to new char.
Competitor::Competitor(char* inputName, int charlen, int inputLane)
{
name = new char[charlen + 1];
memcpy(name , inputName, charlen );
name [charlen] = '\0';
lane = inputLane;
}

C++ change from struct to classes [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I am looking to change this from struct to classes and use a header file to hold the class.
What would you suggest in way of changing it over. The code all works. There is no problem there. just a simple change over question.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
struct printype
{
char dots[8][15];
int unknown15; // can have values of 0..127
string serial11_14; // 8 characters 00000000...99999999
int year8; // without century, 0..99
int month7; // 1..12
int day6; // 1..31
int hour5; // 0..23
int minute2; // 0..59
};
int getunknown15(); // prototypes
string getserial11_14();
int getyear8();
int getmonth7();
int getday6();
int gethour5();
int getminute2();
int setunknown15(int); //------------------------- protos
string setserial11_14(string);
int setyear8(int);
int setmonth7(int);
int setday6(int);
int sethour5(int);
int setminute2(int);
// int array and display info for array
void setup(char[8][15]);
// display array
void darray(char[8][15]);
// displays printer information
void dpinfo(printype);
// set parrity
void spar(char[8][15]);
// fill array
void ftarray(printype &); //----------------------end protos
//-------------------------------------
void main ()
{
printype pt;
pt.unknown15=getunknown15();
pt.unknown15=setunknown15(pt.unknown15);
pt.serial11_14=getserial11_14();
pt.serial11_14=setserial11_14(pt.serial11_14);
pt.year8=getyear8();
pt.year8=setyear8(pt.year8);
pt.month7=getmonth7();
pt.month7=setmonth7(pt.month7);
pt.day6=getday6();
pt.day6=setday6(pt.day6);
pt.hour5=gethour5();
pt.hour5=sethour5(pt.hour5);
pt.minute2=getminute2();
pt.minute2=setminute2(pt.minute2);
cout <<"-----------------------------------------------------"<<endl;
cout <<" Lets Get Started"<<endl;
cout <<"-----------------------------------------------------"<<endl;
setup(pt.dots); // sets up the array
dpinfo(pt); // prints out the final array
ftarray(pt);
spar(pt.dots);
darray(pt.dots);
}
int getunknown15()
{
printype tem;
cout <<"-----------------------------------------------------"<<endl;
cout <<" Enter the Unkown Variable (0-127): ";
cin >>tem.unknown15;
cout <<"-----------------------------------------------------"<<endl;
return tem.unknown15;
}
string getserial11_14()//------------------------------------------ starts the get information sets
{
printype tem;
cout <<" Enter the Serial Variable (8char long): ";
cin >>tem.serial11_14;
cout <<"-----------------------------------------------------"<<endl;
return tem.serial11_14;
}
int getyear8()
{
printype tem;
cout <<" Enter the Year Variable (2char long): ";
cin >>tem.year8;
cout <<"-----------------------------------------------------"<<endl;
return tem.year8;
}
int getmonth7()
{
printype tem;
cout <<" Enter the Month Variable (2char long): ";
cin >>tem.month7;
cout <<"-----------------------------------------------------"<<endl;
return tem.month7;
}
int getday6()
{
printype tem;
cout <<" Enter the Day Variable (2char long): ";
cin >>tem.day6;
cout <<"-----------------------------------------------------"<<endl;
return tem.day6;
}
int gethour5()
{
printype tem;
cout <<" Enter the Hour Variable (2char long): ";
cin >>tem.hour5;
cout <<"-----------------------------------------------------"<<endl;
return tem.hour5;
}
int getminute2()
{
printype tem;
cout <<" Enter the Minute Variable (2char long): ";
cin >>tem.minute2;
cout <<"-----------------------------------------------------"<<endl;
return tem.minute2;
}
//-----------------------------------------------------------put functions (adds info to the array)
int setunknown15(int tem)
{
printype pp;
if (tem>127||tem<0)
{
cout << "Error" << endl;
return 0;
}
else
{
pp.unknown15 = tem;
return pp.unknown15;
}
}
string setserial11_14(string tem)
{
printype pp;
if(tem.size() !=8)
{
cout <<"nope.jpg"<<endl;
return 0;
}
else
{
for (int i = 0; i < 8; i++)
{
if(!isdigit(tem.at(i)))
{
cout<<"nope.jpg"<<endl;
return 0;
}
}
pp.serial11_14=tem;
return pp.serial11_14;
}
}
int setyear8(int tem)
{
printype pp;
if(tem>99||tem<0)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.year8=tem;
return pp.year8;
}
}
int setmonth7(int tem)
{
printype pp;
if(tem>12||tem<1)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.month7=tem;
return pp.month7;
}
}
int setday6(int tem)
{
printype pp;
if(tem>31||tem<1)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.day6=tem;
return pp.day6;
}
}int sethour5(int tem)
{
printype pp;
if(tem>23||tem<0)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.hour5=tem;
return pp.hour5;
}
}
int setminute2(int tem)
{
printype pp;
if(tem>59||tem<0)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
pp.minute2=tem;
return pp.minute2;
}
}
void setup(char tem[8][15])
{
for (int x=0;x<8;x++)// set to all blanks
{
for (int y=0;y<15;y++)
{
tem[x][y]=' ';
}
}
}
void darray(char tem[8][15])
{
for (int x=0;x<8;x++)// set to all blanks
{
cout <<"\t-------------------------------"<<endl;
cout <<"\t|";
for (int y=0;y<15;y++)
{
cout << tem[x][y];
cout<<"|";
}
cout <<"\n";
}
cout <<"\t-------------------------------"<<endl;
}
void dpinfo(printype mc)
{
cout <<"The unknown is:\t"<<mc.unknown15<<"\nThe String is:\t"<<mc.serial11_14<<"\n Time:\n\n Year: 20"<<mc.year8<<" month: "<<mc.month7<<"\n day: "<<mc.day6<<" hour: "<<mc.hour5<<"\n minute: "<<mc.minute2<<endl;
}
void spar(char tem[8][15])
{
int count=0;
for (int x=0;x<7;x++)
{
for (int y=0;y<15;y++)
{
if(tem[x][y]=='*')
{
count+=1;
}
}
if(count%2==0)
{
tem[x][0]='*';
}
}
count=0;
for (int a=0;a<7;a++)
{
for (int z=0;z<7;z++)
{
}
}
}
void ftarray(printype &pt)
{
int tem=0;
for (int x=1;x<15;x++)
{
switch(x)
{
case 1:
{
tem=pt.minute2;
break;
}
case 4:
{
tem=pt.hour5;
break;
}
case 5:
{
tem=pt.day6;
break;
}
case 6:
{
tem=pt.month7;
break;
}
case 7:
{
tem=pt.year8;
break;
}
case 9:
{
for (int j = 1; j < 8; j++)
{
pt.dots[j][x] = '*';
}
}
case 10:
{
tem=atoi(pt.serial11_14.substr(6,2).c_str());
break;
}
case 11:
{
tem=atoi(pt.serial11_14.substr(4,2).c_str());
break;
}
case 12:
{
tem=atoi(pt.serial11_14.substr(2,2).c_str());
break;
}
case 13:
{
tem=atoi(pt.serial11_14.substr(0,2).c_str());
break;
}
case 14:
{
tem=pt.unknown15;
break;
}
}
if(x==1||x==4||x==5||x==6||x==7||x==10||x==11||x==12||x==13||x==14)
{
if (tem>=64)
{
pt.dots[1][x]='*';
tem-=64;
}
if (tem>=32)
{
pt.dots[2][x]='*';
tem-=32;
}
if (tem>=16)
{
pt.dots[3][x]='*';
tem-=16;
}
if (tem>=8)
{
pt.dots[4][x]='*';
tem-=8;
}
if (tem>=4)
{
pt.dots[5][x]='*';
tem-=4;
}
if (tem>=2)
{
pt.dots[6][x]='*';
tem-=2;
}
if (tem>=1)
{
pt.dots[7][x]='*';
tem-=1;
}
}
}
}
In C++, struct and class is the same thing, other than the default access level. All you need to do is replace
struct printype
{
//...
};
with
class printype
{
public:
//...
};
You can also probably replace the functions that take a printype as argument by value with member functions:
void dpinfo(printype);
becomes
class printype
{
public:
//....
void dpinfo();
};
and will operate on this rather than the parameter.
Methods that return an object printype can become constructors.
I suspect however you have several issues with your code:
int getunknown15()
{
printype tem;
cout <<"-----------------------------------------------------"<<endl;
cout <<" Enter the Unkown Variable (0-127): ";
cin >>tem.unknown15;
cout <<"-----------------------------------------------------"<<endl;
return tem.unknown15;
}
Here, for example, you don't need the tem variable... it does nothing. You can directly read an int an return that, tem will be destroyed on function exit anyway.
Maybe you're looking for a member function, for example:
int printype::setyear8(int tem)
{
if(tem>99||tem<0)
{
cout<<"nope.jpg"<<endl;
return 0;
}
else
{
this->year8=tem;
return this->year8;
}
}
This way the object is modified and you don't lose changes. However, your coding style suggests little to no knowledge of oop. I suggest reading a good book before continuing, as I doubt that, as it is, the answer will make much sense to you.
First of all, a struct and a class are the same in C++, only difference is that a struct is default public and a class is default private. All you do is change struct to class
Looking at your code, however, I'm assuming you are converting from C to C++ and want to add your functions as methods to the class. To do this, you simply add the prototypes to the class declaration and then add the class space to the function implementations. You should also add any relevant constructors and a destructor in necessary
In a h file
class Printype {
char **dots;
int unknown15; // can have values of 0..127
string serial11_14; // 8 characters 00000000...99999999
int year8; // without century, 0..99
int month7; // 1..12
int day6; // 1..31
int hour5; // 0..23
int minute2; // 0..59
//Constructors
Printype(); //Default
Printype(const Printype &cpy); //Copy
Printype(int yr, int mo, int d, int hr, int min); //Sample initializer
//Destrutor
~Printype();
//Methods (only gonna do 2 for example)
int getYear();
void setYear(int y);
};
In a cpp or cc file
#include "printype.h"
Printype::Printype() {
dots = new char*[8];
for(int i=0;i<8;++i) {
dots[i] = new char[15];
}
unknown15 = 0; serial11_14 = ""; year8 = 0;
month7 = 0; day6 = 0; hour5 = 0;minute2 = 0;
}
Printype::Printype(const Printype &cpy) {
//Deep copy all values from cpy to this
}
Printype::Printype() {
dots = new char*[8];
for(int i=0;i<8;++i) {
dots[i] = new char[15];
}
unknown15 = 0; serial11_14 = ""; year8 = yr;
month7 = mo; day6 = d; hour5 = hr;minute2 = min;
}
//Destructor (free allocated memory)
Printype::~Printype() {
for(int i=0;i<8;++i) {
delete[] dots[i]; dots[i] = NULL;
}
delete[] dots; dots = NULL;
}
//Methods
int Printype::getYear() {
return year8;
}
void Printype::setYear(int y) {
year8 = y;
}
You should also implement an = operator. Hope this gets you started and answers your question though. You should really read up on some general OOP in addition to C++ syntax, patterns, etc. A lot of this will likely look foreign and not make much sense, and it will take to long to explain in this forum. There are tons of resources online regarding this material so you should try to read up on it.