Tic Tac Toe array wrong characters - c++

The screenshot says it all, the characters i use are correctly put inside the array. However, some other random characters are inserted in the array as well. I'm confused!
main.cpp :
#include "Players.h"
#include "GameLayout.h"
#include "Game.h"
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char gameBoard [3][3];
cout << "**** Welcome to Leviathan's first TicTacToe Game! ****\n\n";
Players playersObject;
playersObject.getPlayersNames();
playersObject.printPlayersNames();
GameLayout gameObject;
gameObject.printLayout();
Game gamestartObject;
gamestartObject.gameStart(gameBoard);
}
game.cpp :
#include "Players.h"
#include "GameLayout.h"
#include "Game.h"
#include <iostream>
#include <string>
using namespace std;
void Game::gameStart(char board[3][3])
{
char player1char,player2char;
size_t i,j;
cout << "Enter player 1 character :";
cin >> player1char;
cout << "Enter player 2 character :";
cin >> player2char;
int row,column;
bool isDone = false;
while(isDone == false)
{
cout << "Player 1->choose row";
cin >> row;
cout << "Player 1->choose column";
cin >> column;
board[row-1][column-1] = player1char;
cout << "Player 2->choose row";
cin >> row;
cout << "Player 2->choose column";
cin >> column;
board[row-1][column-1] = player2char;
GameLayout layout;
cout << " |1||2||3|" <<endl;
for(i=0; i<3; i++)
{
cout << i+1 << "|";
for(j=0; j<3; j++)
{
cout <<" "<<board[i][j] << " " ;
}
cout << endl;
}
}
}
Players.cpp :
#include "Players.h"
#include "GameLayout.h"
#include "Game.h"
#include <iostream>
#include <string>
using namespace std;
void Players::getPlayersNames()
{
string p1,p2;
cout << "Enter player 1 name : ";
cin >> p1;
cout << "\nEnter player 2 name : ";
cin >> p2;
_player1Name = p1;
_player2Name = p2;
}
void Players::printPlayersNames()
{
cout << "Alright " << _player1Name << " and " << _player2Name <<", the game has begun!\n\n";
}
GameLayout.cpp :
#include "Players.h"
#include "GameLayout.h"
#include "Game.h"
#include <iostream>
#include <string>
using namespace std;
void GameLayout::printLayout()
{
size_t i,j;
char board[3][3];
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
board[i][j] = '.';
}
}
cout << " |1||2||3|" <<endl;
for(i=0; i<3; i++)
{
cout << i+1 << "|";
for(j=0; j<3; j++)
{
cout <<" "<<board[i][j] << " " ;
}
cout << endl;
}
}
Game.h :
#ifndef GAME_H
#define GAME_H
class Game
{
public:
void gameStart(char board[3][3]);
private:
};
#endif // GAME_H
GameLayout :
#ifndef GAMELAYOUT_H
#define GAMELAYOUT_H
class GameLayout
{
public:
void printLayout();
private:
};
#endif // GAMELAYOUT_H
Players.h :
#ifndef PLAYERS_H
#define PLAYERS_H
#include <string>
class Players
{
public:
void getPlayersNames();
void printPlayersNames();
private:
std::string _player1Name;
std::string _player2Name;
};
#endif // PLAYERS_H

Local non-static variables in a function, like e.g. gameBoard, are not initialized. You need to explicitly initialize it, or its contents will be indeterminate and reading its values will lead to undefined behavior.
You can simply do it like
char gameBoard [3][3] = { ' ' };

Related

How to initialize private variables in a different file and make it so it holds the value for other functions?

I just need to know how to have size, index, and counter keep their values when they are called in another function. Right now they are just being given random values when they are called instead of the values I'm initializing them with in the constructor. How can I fix this? The objective for this code is to make a program that Captures a string of words from a user of the program (via the keyboard) and adds the entered
words to a dynamic array of strings.
This is the array.cpp file
#include "array.h"
using namespace std;
Array::Array()
{
int size = 100;
int index = 0;
int counter = 0;
counter ++;
index++;
string *ptr = new string[size];
}
Array::~Array()
{
delete ptr;
ptr = nullptr;
}
void Array::populate()
{
string word;
cout << "Enter word to add to array: ";
cin >> word;
ptr[index] = word;
}
void Array::printContent()
{
cout << "Number of words in array: " << counter << endl;
cout << "Array size: " << size << endl;
cout << "Words in array: " << endl;
for (int i = 0; i < counter; i++)
{
cout << ptr[i] << endl;
}
}
void Array::displayMenu() const
{
cout << "[1] Add Word\n"
<< "[2] Print Array Information\n"
<< "[3] Quit Program\n"
<< "Enter Choice: ";
}
int Array::getChoice(int & choice1)
{
cin >> choice1;
while (choice1 < 1 || choice1 > 3) {
cout << endl;
cout << "Invalid Entry!!" << endl;
cout << "Enter Choice: ";
cin >> choice1;
}
return choice1;
}
int Array::endProgram(int & start2)
{
start2 = 0;
cout << "\n\n\t\tThank you for using this system!!\n\n";
return start2;
}
This is the array.h file
#include <iostream>
#include <string>
using namespace std;
class Array {
public:
Array();
~Array();
void populate();
void printContent();
void displayMenu() const;
int getChoice(int & choice1);
int endProgram(int & start2);
private:
int size;
int index;
int counter;
string *ptr;
};
Lastly this is the main.cpp file
#include <iostream>
#include "array.h"
using namespace std;
int main() {
int choice = 0;
int start = 1;
Array theArray;
while(choice != 3)
{
theArray.displayMenu();
theArray.getChoice(choice);
if(choice == 1)
{
theArray.populate();
}
if(choice == 2)
{
theArray.printContent();
}
if (choice == 3)
{
theArray.endProgram(start);
}
}
}
You are defining new local variables inside of your Array constructor and shadowing the member variables of the same name -- which is why the value isn't being preserved.
You only need to specify the type when defining new variables, but not when assigning to existing ones. To assign to the member variables, this should be:
Array::Array()
{
size = 100;
index = 0;
counter = 0;
ptr = new string[size];
...
}
Additionally, in constructors its more correct to use constructor initializer lists to initialize the values:
Array::Array()
: size{100},
index{0},
counter{0},
ptr{new string[size]}
{
...
}

Output not coming as expected for function call inside loop

#include <iostream>
#include <vector>
#include <set>
#include <list>
#include <map>
#include <cmath>
#include <queue>
#include <vector>
#include <memory>
#include "C:\Users\HP\Documents\Dreyfus-Wagner\Dijkstra.h"
using namespace std;
#define MAX 100001
#define pir pair<int, int>
#define pbd(x) push_back(x)
using namespace std;
#define MAX 100001
#define pir pair<int, int>
#define pbd(x) push_back(x)
struct Out
{
int *p;
};
vector<pir> Graph[MAX];
int main()
{
int nodes1, edges1, starting1;
// create graph
cout << "Enter the number of vertices and edges: ";
cin >> nodes1 >> edges1;
cout << "Enter the edges with weigth: <source> <destination> <weigth>: \n";
int u1, v1, w1;
struct Out output[nodes1];
int adjMatrix[nodes1][nodes1];
for (int i = 0; i < edges1; i++)
{
cin >> u1 >> v1 >> w1;
Graph[u1].pbd(pir(v1, w1));
Graph[v1].pbd(pir(u1, w1)); // for undirected
}
cout << "Enter the source node: ";
cin >> starting1;
for (int i = 1; i <= nodes1; i++)
{
output[i].p = Djiktra(nodes1, edges1, i, Graph);
}
for (int j = 1; j <= nodes1; j++)
{
for (int i = 1; i <= nodes1; i++)
{
cout << "*(p + " << i << ") : ";
cout << *(output[j].p + i) << endl;
;
}
cout << " " << endl;
}
}
If we call the single instance of function it gives correct output.
Note : Djiktra function is stored in another file that is referred in header. The idea is that to find shortest lengths of elements per node
Could anyone explain why the output is incorrect when called inside for loop?

How to display my Queue & Stack?

I Wanna display my EvenQueue, EvenStack, OddQueue & EvenQueue? I already try some methods but the compiler gave me some errors.
Any help would be appreciated... Or any tips.
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
int main()
{
stack<int> OddStack;
queue<int> OddQueue;
stack<int> EvenStack;
queue<int> EvenQueue;
int MyNumbers[10];
int InNum;
for(int i = 0; i < 10; i++)
{
cout << "Enter Number " << i << ": ";
cin >> InNum;
MyNumbers[i] = InNum;
if(InNum % 2 == 0)
{
EvenQueue.push(InNum);
EvenStack.push(InNum);
}
else
{
OddQueue.push(InNum);
OddStack.push(InNum);
}
}
cout << "Stack" << "\t\t" << "Queue" << endl;
return 0;
}
Assign it to tempstack
stack<int>tempStack = OddStack
and start poping from it and see what is inside
while(tempStack.empty() == false){
int x = tempStack.top();
cout << x << endl;
tempStack.pop();
}
same goes for the queue

Program for a Vector of Strings

I created a program that asks the user to enter 5 names which is recorded into a vector of strings. Afterwards the program is supposed to grab the first and last letters of each name and output them. My program compiles fine however after entering the names I get no output from the program.
Can anyone help me correct this issue so that it prints the first and last characters of each name entered?
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> names;
char first_letter;
char last_letter;
string name;
int n = 0;
for (int i =0; i < 5; i++)
{
cout << " Please enter a name: ";
cin >> name;
names.push_back(name);
}
if ( !names[n].empty() )
{
first_letter = *names[n].begin();
last_letter = *names[n].rbegin();
cout << first_letter << " " << last_letter << endl;
n++;
}
return 0;
}
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> names;
char first_letter;
char last_letter;
string name;
int n = 0;
for (int i =0; i < 5; i++)
{
cout << " Please enter a name: ";
cin >> name;
names.push_back(name);
}
vector<string>::iterator itr = names.begin();
for(;itr!=names.end();itr++)
{
first_letter = *itr[n].begin();
last_letter = *itr[n].rbegin();
cout << first_letter << " " << last_letter << endl;
}
return 0;
}
You have entered it as a if statement. Change it to a while loop
while ( !names[n].empty() )
{
first_letter = *names[n].begin();
last_letter = *names[n].rbegin();
std::cout << first_letter << " " << last_letter << endl;
n++;
}

C++ program doesn't print out strings but does output double value

So here is the program I'm working on. So far it just prints out the double value in my CPP file. Note the two characters arrays I have set up. Why is this?
Molecule.h
const int MAX_STRUCT = 10;
const int MAX_NAME = 20;
class Molecule {
char molecule_structure[];
char molecule_name[];
double molecule_mass;
public:
Molecule();
bool read();
void display() const;
};
Molecule.cpp
#include <iostream>
#include <cstring>
using namespace std;
#include "Molecule.h"
Molecule::Molecule() {
molecule_structure[0] = '\0';
molecule_name[0] = '\0';
molecule_mass = 0;
}
bool Molecule::read(){
bool complete = false;
cout << "Enter structure : ";
cin.getline (molecule_structure, 10);
if (strcmp (molecule_structure, "0") != 0){
cout << "Enter full name : ";
cin.getline (molecule_name, 20);
cout << "Enter weight : ";
cin >> molecule_mass;
cin.ignore();
complete = true;
}
else {
molecule_structure[0] = '\0';
molecule_name[0] = '\0';
molecule_mass = 0;
}
return complete;
}
void Molecule::display() const
{
cout << molecule_structure << " " << molecule_name << " " << molecule_mass << endl;
}
w4x.h
const int MAX_MOLECULES = 10;
w4x.cpp
#include <iostream>
using namespace std;
#include "w4x.h"
#include "Molecule.h"
int main() {
int n = MAX_MOLECULES;
Molecule molecule[MAX_MOLECULES];
cout << "Molecular Information\n";
cout << "=====================" << endl;
for (int i = 0; i < MAX_MOLECULES; i++) {
if (!molecule[i].read()) {
n = i;
i = MAX_MOLECULES;
}
cout << endl;
}
cout << "Structure Name Mass\n";
cout << "==================================================" << endl;
for (int i = 0; i < n; i++)
molecule[i].display();
}
The errors I believe are coming from my Molecule.cpp file which is what I've been changing around.
This is the output I'm currently receiving.
Molecular Information
=====================
Enter structure : Super
Enter full name : Man
Enter weight : 57
Enter structure : 0
Structure Name Mass
==================================================
57
Changing the header Molecule.h so it uses:
const int MAX_STRUCT = 10;
const int MAX_NAME = 20;
class Molecule {
char molecule_structure[MAX_STRUCT];
char molecule_name[MAX_NAME];
double molecule_mass;
public:
Molecule();
bool read();
void display() const;
};
Makes the code work sanely.
A more thorough reworking of the code to use std::string gives:
Molecule.h
#ifndef MOLECULE_H_INCLUDED
#define MOLECULE_H_INCLUDED
#include <string>
class Molecule
{
std::string molecule_structure;
std::string molecule_name;
double molecule_mass;
public:
Molecule();
bool read();
void display() const;
};
#endif // MOLECULE_H_INCLUDED
Molecule.cpp
#include <iostream>
#include <iomanip>
#include <limits>
#include <cstring>
using namespace std;
#include "Molecule.h"
Molecule::Molecule() : molecule_structure(""), molecule_name(""), molecule_mass(0) { }
bool Molecule::read()
{
Molecule m;
cout << "Enter structure : ";
if (!getline(cin, m.molecule_structure) || m.molecule_structure == "")
return false;
cout << "Enter full name : ";
if (!getline(cin, m.molecule_name))
return false;
cout << "Enter weight : ";
if (!(cin >> m.molecule_mass))
return false;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
swap(*this, m);
return true;
}
void Molecule::display() const
{
cout << left << setw(15) << molecule_structure << " ";
cout << left << setw(20) << molecule_name << " ";
cout << setprecision(5) << molecule_mass << endl;
}
The read() function does not modify the variable it is given unless the reading is successful. There are probably better ways to handle the input, but that shown is reasonably sensible. You terminate the input with an empty line in response to the 'Enter structure:' prompt. The printf() format notations have the merit of brevity compared with what's necessary with C++ I/O streams.
w4x.cpp
No longer including w4x.h.
#include <iostream>
using namespace std;
#include "Molecule.h"
const int MAX_MOLECULES = 10;
int main()
{
int n = MAX_MOLECULES;
Molecule molecule[MAX_MOLECULES];
cout << "Molecular Information\n";
cout << "=====================" << endl;
for (int i = 0; i < MAX_MOLECULES; i++) {
if (!molecule[i].read()) {
n = i;
break;
}
cout << endl;
}
if (n > 0)
{
cout << "Structure Name Mass\n";
cout << "===================================================" << endl;
for (int i = 0; i < n; i++)
molecule[i].display();
}
}