C++ do while keeps repeating - c++

#include <iostream>
#include <string>
#include <cctype>
#include <sstream>
using namespace std;
int getTreeNo(int);
int getSpeciesCode(int);
float getDbh(float);
int getTotHt(int);
int getTotHt(int);
double calcTotVol(double[], double[], float, int);
int main() {
int i = 0;
int treeNo = 0;
int speciesCode = 0;
string speciesDesc[6] = {};
float dbh = 0.00;
int totalHt = 0;
double totalVol = 0.00;
int Species[6] = {};
double b0[6] = {};
double b1[6] = {};
int noTrees = 0;
treeNo = getTreeNo(treeNo);
/* Gets number of trees for calculations*/
speciesCode = getSpeciesCode(speciesCode);
/* Get Species code from user*/
dbh = getDbh(dbh);
/* get DBH from user*/
totalHt = getTotHt(totalHt);
/*Gets tree height from user*/
totalVol = calcTotVol(b0, b1, dbh, totalHt);
/* Calculates values */
/* All constants and variables
int treeNo;
int speciesCode;
string speciesDesc[6];
float dbh;
int totalHt;
double totalVol;
int Species[6];
double b0[6];
double b1[6];
int noTrees;
double avgTotVol;
*/
if (speciesCode = 11) {
speciesDesc[0] = "Loblolly Pine";
} else if (speciesCode = 12) {
speciesDesc[1] = "White Pine";
} else if (speciesCode = 13) {
speciesDesc[2] = "Red Pine";
} else if (speciesCode = 21) {
speciesDesc[3] = "White Oak";
} else if (speciesCode = 22) {
speciesDesc[4] = "Red Oak";
} else if (speciesCode = 23) {
speciesDesc[5] = "Other Oak";
}
Species[0] = 11;
Species[1] = 12;
Species[2] = 13;
Species[3] = 21;
Species[4] = 22;
Species[5] = 23;
if (speciesCode = 11) {
b0[0] = 1.2446;
} else if (speciesCode = 12) {
b0[1] = 0.000;
} else if (speciesCode = 13) {
b0[2] = 2.0822;
} else if (speciesCode = 21) {
b0[3] = .7316;
} else if (speciesCode = 22) {
b0[4] = 1.6378;
} else if (speciesCode = 23) {
b0[5] = .7554;
}
if (speciesCode = 11) {
b1[0] = .002165;
} else if (speciesCode = 12) {
b1[1] = .002364;
} else if (speciesCode = 13) {
b1[2] = .002046;
} else if (speciesCode = 21) {
b1[3] = .001951;
} else if (speciesCode = 22) {
b1[4] = .002032;
} else if (speciesCode = 23) {
b1[5] = .002174;
}
totalVol = b0[6] + b1[6] * pow(dbh, 2) * totalHt;
for (i = 0; i < treeNo; i++) {
cout << "Tree Number " << i + 1 << ": " << speciesCode << dbh << totalHt
<< speciesDesc[6] << b0[6] << b1[6] << totalVol;
}
}
/************************************************************************************************
* *************/
int getTreeNo(int treeNo) {
do {
cout << "Please enter the number of trees :" << endl;
cin >> treeNo;
if ((treeNo <= 0) || (treeNo > 999)) {
cout << "ERROR!!!,You cannot have more then999 entries" << endl;
}
} while ((treeNo <= 0) || (treeNo > 999));
return treeNo;
}
int getSpeciesCode(int speciesCode) {
do {
cout << "Please enter your Species Code";
cin >> speciesCode;
} while ((speciesCode != 11) || (speciesCode != 12) ||
(speciesCode != 13) || (speciesCode != 21) ||
(speciesCode != 22) || (speciesCode != 23));
cout << "ERROR!!!,That information does not exist wthin our system" << endl;
return speciesCode;
}
float getDbh(float dbh) {
do {
cout << "Please enter the DBH of the tree, The DBH must be greter then "
"and equal to five and less then 50.6" << endl;
cin >> dbh;
if ((dbh < 5) || (dbh > 50.6)) {
cout << "ERROR!!!, The DBH must be greter then and equal to five "
"and less then 50.6" << endl;
}
} while ((dbh < 5) || (dbh > 50.6));
return dbh;
}
int getTotHt(int totalHt) {
do {
cout << "Please enter the height of the tree" << endl;
cin >> totalHt;
if ((totalHt < 24) || (totalHt > 160)) {
cout << "ERROR!!!, Please enter a height thats not larger then "
"160, but greater then 24" << endl;
}
} while (totalHt < 24 || totalHt > 160);
{ return totalHt; }
}
double calcTotVol(double array[], double array1[], float dbh, int totalHt) {
double totalVol;
totalVol = array[6] + array1[6] * pow(dbh, 2) * totalHt;
return totalVol;
}
can anyone help me my speciesCode function keeps looping and will not accept my input actually I do not believe any function is accepting it I have worked for hours to try to figure out why and am stuck
thanks for any help

the condition in this while statement will never ever be false, and your loop will never exit. In order for it to be false, speciesCode has to have more than 1 value at a time.
while((speciesCode != 11) || (speciesCode != 12) || (speciesCode != 13) || ...)
You probably want to keep repeating until you get a valid code. In that case use &&
while((speciesCode != 11) && (speciesCode != 12) && (speciesCode != 13) && ...)

Related

How to randomize the creation of objects of different classes? c++

I'm doing project with classes in c++ which consists of a car that avoids obstacles on a board. I want to randomize the appearance of the object of classes EnemiesCar, Nail, Hole (the last two are subclasses of the first). The problem is that when i generate random number, it change too fast and the object that had appeared then disappears (the objects on the board come out intermittently between other object because the random number changes too fast). How can I fix this problem? Are there other solution for randomize objects of class? (I tried to do this function in Game::randomAppear(EnemiesCar &myEn, Nail &myNe, Hole &myHo), below I leave only the class EnemiesCar because its subclasses are similar).
Game.cpp
#include "Game.h"
#include "Nail.h"
#include "EnemiesCar.h"
#include "Car.h"
#include "Hole.h"
#include <windows.h>
#include <iostream>
#include <thread>
#include <stdlib.h> /* srand, rand */
#include <ctime>
using namespace std;
Game::Game(){
running = true;
counter = 100;
maxScore = 0;
maxLevel = 1;
timeS = 100.0;
level = 1;
levelUp = 1000;
levelDown = 0;
}
void Game::gotoXY(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void Game::resetBoard()
{
for(int j=0;j<20;j++){
for(int i=1;i<20;i++){
matrix[i][j]=0;
}
}
}
void Game::createTab()
{
for(int j=0;j<20;j++){
for(int i=0;i<21;i++){
if(i==0 || i==20){
gotoXY(i,j);
cout<<"b";
}else if(j == 19){
gotoXY(i,j);
cout<<"*";
}else if(matrix[i][j]==1){
gotoXY(i,j);
cout<<"m";
}else if(matrix[i][j]==2){
gotoXY(i,j);
cout<<"e";
}else if(matrix[i][j]==3){
gotoXY(i,j);
cout<<"c";
}else if(matrix[i][j]==4){
gotoXY(i,j);
cout<<"h";
}else {
gotoXY(i,j);
cout<<" ";
}
}
}
}
void Game::checkSamePosition(EnemiesCar EN, Nail NE)
{
if(NE.xPos == EN.xPos && NE.yPos == EN.yPos){
NE.xPos = NE.xPos + 2;
}
}
int Game::checkMaxScore()
{
if(maxScore < counter){
maxScore = counter;
}
return maxScore;
}
int Game::checkMaxLevel()
{
if(maxLevel < level){
maxLevel = level;
}
return maxLevel;
}
void Game::TabLevelUp()
{
system("cls");
gotoXY(5, 5);
cout << "Next Level" << endl;
gotoXY(5, 7);
cout << "Level: " << level;
}
void Game::TabLevelDown()
{
system("cls");
gotoXY(5, 5);
cout << "Previous Level" << endl;
gotoXY(5, 7);
cout << "Level: " << level;
}
void Game::gameLevels(Car &car)
{
if(counter == levelUp){
level++;
TabLevelUp();
Sleep(5000);
gotoXY(40, 9);
cout << "level " << level;
levelDown = levelUp;
levelUp = levelUp + 1000;
gotoXY(40, 10);
cout << "next " << levelUp;
if(timeS >= 40){
double update = timeS - 20.0;
timeS = update;
gotoXY(40, 7);
cout << "tmpIf " << timeS;
Sleep(update);
}else if(timeS == 20 || timeS == 30){
double update = timeS - 10.0;
timeS = update;
gotoXY(40, 7);
cout << "tmpIf " << timeS;
Sleep(update);
}else if(timeS >= 10 && timeS < 20){
double update = timeS - 5.0;
timeS = update;
gotoXY(40, 7);
cout << "tmpIf " << timeS;
Sleep(update);
}else if(timeS == 0){
Sleep(timeS);
}else{
double update = timeS - 0.5;
timeS = update;
gotoXY(40, 7);
cout << "tmpIf " << timeS;
Sleep(update);
}
playGame(car);
}else if(counter < levelDown){
level--;
TabLevelDown();
Sleep(5000);
levelUp = levelDown;
levelDown = levelDown - 1000;
if(timeS >= 40 && timeS < 100){
double update = timeS + 20.0;
timeS = update;
gotoXY(45, 7);
cout << "tmpIf " << timeS;
Sleep(update);
}else if(timeS == 20 || timeS == 30){
double update = timeS + 10.0;
timeS = update;
gotoXY(45, 7);
cout << "tmpIf " << timeS;
Sleep(update);
}else if(timeS == 10 && timeS < 20){
double update = timeS + 5.0;
timeS = update;
gotoXY(45, 7);
cout << "tmpIf " << timeS;
Sleep(update);
}else if(timeS < 10 && level <= 17){
double update = timeS + 0.5;
timeS = update;
gotoXY(45, 7);
cout << "tmpIf " << timeS;
Sleep(update);
}else{
Sleep(timeS);
}
playGame(car);
}else{
Sleep(timeS);
}
}
void Game::showLevelScore()
{
gotoXY(50, 1);
cout<<"Score: " << counter;
gotoXY(50, 3);
cout<<"Level: " << level;
}
void Game::gameEnd()
{
if(counter <= 0){
running = false;
Sleep(1000);
system("cls");
gotoXY(5,4);
cout << "GAME OVER!!!";
gotoXY(5,6);
cout << "MAX LEVEL: " << checkMaxLevel();
gotoXY(5,7);
cout << "MAX SCORE: " << checkMaxScore();
gotoXY(0,0);
}
}
int Game::generateRandomNumber()
{
int rEne = rand() % 3;
gotoXY(50, 5);
cout << "R: " << rEne << endl;
return rEne;
}
void Game::randomAppear(EnemiesCar &myEn, Nail &myNe, Hole &myHo)
{
int rEne = generateRandomNumber();
if(rEne == 0){
myEn.appear();
myEn.drawEnemies(myEn.xPos, myEn.yPos, matrix);
myEn.move();
}else if(rEne == 1){
myNe.appear();
myNe.drawNails(myNe.xPos, myNe.yPos, matrix);
myNe.move();
}else{
myHo.appear();
myHo.drawHoles(myHo.xPos, myHo.yPos, matrix);
myHo.move();
}
}
void Game::playGame(Car &mycar){
EnemiesCar myEnmCar = EnemiesCar();
Nail nails = Nail();
Hole holes = Hole();
while(this->running){
srand (time(NULL));
resetBoard();
randomAppear(myEnmCar, nails, holes);
checkSamePosition(myEnmCar, nails);
/*myEnmCar.appear();
myEnmCar.drawEnemies(myEnmCar.xPos, myEnmCar.yPos, matrix);
myEnmCar.move();*/
/*gotoXY(3, 22);
cout << "enmpos: " << myEnmCar.xPos << myEnmCar.yPos << endl;*/
/*nails.appear();
nails.drawNails(nails.xPos, nails.yPos, matrix);
nails.move();
holes.appear();
holes.drawHoles(holes.xPos, holes.yPos, matrix);
holes.move();*/
mycar.drawCar(mycar.xPos, mycar.yPos, matrix);
mycar.checkCollusion(myEnmCar, nails, holes, &counter, &level);
createTab();
myEnmCar.addScore(mycar, &counter);
nails.addScore(mycar, &counter);
holes.addScore(mycar, &counter);
showLevelScore();
checkMaxLevel();
checkMaxScore();
gameEnd();
gameLevels(mycar);
}
}
void Game::startGame()
{
srand (time(NULL));
Car mycar = Car();
thread myThread(&Car::myListener, &mycar, &mycar);
playGame(mycar);
Sleep(5000);
myThread.detach();
}
EnemiesCar.h
#ifndef ENEMIESCAR_H
#define ENEMIESCAR_H
#include "Game.h"
class Game;
class Car;
class Nail;
class EnemiesCar
{
public:
const int xInit[9] = {2, 4, 6, 8, 10, 12, 14, 16, 18};
int xPos;
int yPos;
Game games = Game();
EnemiesCar();
void appear();
void drawEnemies(int x, int y, int myMatr[21][20]);
//void draw();
void move();
void addScore(Car car, int *countScore);
};
#endif // ENEMIESCAR_H
EnemiesCar.cpp
#include <windows.h>
#include <iostream>
#include "EnemiesCar.h"
#include "Game.h"
#include "Car.h"
#include "Nail.h"
using namespace std;
EnemiesCar::EnemiesCar()
{
int randomX = rand() % 6;
xPos=xInit[randomX];
yPos=0;
}
/*void EnemiesCar::drawEnemies(int x, int y)
{
Game games = Game();
if(y<20 && y>=-0){
games.matrix[x][y] = 2;
cout << "drawEne" <<endl;
}
}*/
void EnemiesCar::appear()
{
if(yPos==18){
int randomNo = rand() % 21;
/*games.gotoXY(35, 7);
cout << "a: " << randomNo << " ";*/
if(randomNo >= 0 && randomNo <= 3){
xPos = 2;
}else if(randomNo == 4 || randomNo == 5){
xPos = 4;
}else if(randomNo == 6 || randomNo == 7){
xPos = 6;
}else if(randomNo == 8 || randomNo == 9){
xPos = 8;
}else if(randomNo == 10 || randomNo == 11){
xPos = 10;
}else if(randomNo == 12 || randomNo == 13){
xPos = 12;
}else if(randomNo == 14 || randomNo == 15){
xPos = 14;
}else if(randomNo == 16 || randomNo == 17){
xPos = 16;
}else{
xPos = 18;
}
yPos = -3;
}
}
void EnemiesCar::drawEnemies(int x, int y, int myMatr[21][20])
{
if(y<20 && y>=-0){
myMatr[x][y] = 2;
myMatr[x-1][y+1] = 2;
myMatr[x+1][y+1] = 2;
myMatr[x][y+1] = 2;
myMatr[x][y+2] = 2;
}
}
void EnemiesCar::move()
{
yPos++;
}
void EnemiesCar::addScore(Car car, int *countScore)
{
if((this->xPos <= car.xPos-3 && this->yPos == 16) || (this->xPos >= car.xPos+3 && this->yPos == 16)){
*countScore = *countScore + 100;
}
}
It seems that what you need to do is separate the appearance/drawing from the generation of the random number. You need to keep track of the "random enemies" you've already generated, and take them - and only them - into account when drawing your board; and independently of this, once every few turns or when triggered by appropriate events, generate a new random enemy/car/whatever, adding it to the set of already-generated ones.

Function displaying an odd cout

I'm trying to make sure that my code works correctly so I am having my bool functions print the true or false that they are returning. However, my function checkColSum which checks to see if every column in my parallel array adds up to 15 is printing three trues and a false when I enter the numbers:
4 9 2
3 5 7
8 1 6
I would really appreciate any help regarding this issue. I just can't seem to figure out what's going wrong.
#include <iostream>
using namespace std;
// Global constants
const int ROWS = 3; // The number of rows in the array
const int COLS = 3; // The number of columns in the array
const int MIN = 1; // The value of the smallest number
const int MAX = 9; // The value of the largest number
// Function prototypes
bool isMagicSquare(int arrayRow1[], int arrayRow2[], int arrayRow3[], int size);
bool checkRange(int arrayRow1[], int arrayRow2[], int arrayRow3[], int size, int min, int max);
bool checkUnique(int arrayRow1[], int arrayRow2[], int arrayRow3[], int size);
bool checkRowSum(int arrayrow1[], int arrayrow2[], int arrayrow3[], int size);
bool checkColSum(int arrayrow1[], int arrayrow2[], int arrayrow3[], int size);
bool checkDiagSum(int arrayrow1[], int arrayrow2[], int arrayrow3[], int size);
void fillArray(int arrayRow1[], int arrayRow2[], int arrayRow3[], int size);
void showArray(int arrayrow1[], int arrayrow2[], int arrayrow3[], int size);
int main()
{
/* Define a Lo Shu Magic Square using 3 parallel arrays corresponding to each row of the grid */
int magicArrayRow1[COLS], magicArrayRow2[COLS], magicArrayRow3[COLS];
// Your code goes here
int repeat = 1;
while (repeat == 1) {
fillArray(magicArrayRow1, magicArrayRow2, magicArrayRow3, 3);
showArray(magicArrayRow1, magicArrayRow2, magicArrayRow3, 3);
/*TESTING DELETE BEFORE TURNING IN*/
checkRange(magicArrayRow1, magicArrayRow2, magicArrayRow3, 3, 1, 9); //works
cout << endl;
checkUnique(magicArrayRow1, magicArrayRow2, magicArrayRow3, 3); //doesnt work
cout << endl;
checkRowSum(magicArrayRow1, magicArrayRow2, magicArrayRow3, 3);//works
cout << endl;
checkColSum(magicArrayRow1, magicArrayRow2, magicArrayRow3, 3); //works?? maybe??
/*TESTING DELETE BEFORE TURNING IN*/
if (isMagicSquare(magicArrayRow1, magicArrayRow2, magicArrayRow3, 3) == true) {
cout << endl << "This is a Lo Shu magic square.";
}
else {
cout << endl << "This is not a Lo Shu magic square.";
}
cout << endl << "Would you like to try again? Enter 1 for yes or 0 for no: ";
cin >> repeat;
}
return 0;
}
// Function definitions go here
bool isMagicSquare(int arrayRow1[], int arrayRow2[], int arrayRow3[], int size)
{
bool trueFalse = false;
if (checkRange(arrayRow1, arrayRow2, arrayRow3, 3, 1, 9) == true && checkUnique(arrayRow1, arrayRow2, arrayRow3, 3) == true) {
if (checkRowSum(arrayRow1, arrayRow2, arrayRow3, 3) == true && checkColSum(arrayRow1, arrayRow2, arrayRow3, 3) == true) {
if (checkDiagSum(arrayRow1, arrayRow2, arrayRow3, 3) == true) {
trueFalse = true;
}
}
}
return trueFalse;
}
bool checkRange(int arrayRow1[], int arrayRow2[], int arrayRow3[], int size, int min, int max)
{
bool inRange = true;
int count = 0;
while (inRange && count < size) {
if (arrayRow1[count] < min || arrayRow1[count] > max) {
inRange = false;
}
count++;
}
while (inRange && count < size) {
if (arrayRow2[count] < min || arrayRow2[count] > max) {
inRange = false;
}
count++;
}
while (inRange && count < size) {
if (arrayRow3[count] < min || arrayRow3[count] > max) {
inRange = false;
}
count++;
}
if (inRange == true) {// TEST
cout << "true";
}
if(inRange == false) {
cout << "false";
}
return inRange;
}
bool checkUnique(int arrayRow1[], int arrayRow2[], int arrayRow3[], int size)
{
bool isUnique = false;
int count = 0;
int one = 0;
int two = 0;
int three = 0;
int four = 0;
int five = 0;
int six = 0;
int seven = 0;
int eight = 0;
int nine = 0;
for (int i = 0; i < size; i++)
{ //checks row 1
if (arrayRow1[i] == 1) { //checks if row one contains the value 1 in any position
one++;
}
if (arrayRow1[i] == 2) {
two++;
}
if (arrayRow1[i] == 3) {
three++;
}
if (arrayRow1[i] == 4) {
four++;
}
if (arrayRow1[i] == 5) {
five++;
}
if (arrayRow1[i] == 6) {
six++;
}
if (arrayRow1[i] == 7) {
seven++;
}
if (arrayRow1[i] == 8) {
eight++;
}
if (arrayRow1[i] == 9) {
nine++;
}
}
for (int i = 0; i < size; i++) { //checks row 2
if (arrayRow1[i] == 1) { //checks if row two contains the value 1 in any position
one++; //if the value 1 is present, a count is added
}
if (arrayRow2[i] == 2) {
two++;
}
if (arrayRow2[i] == 3) {
three++;
}
if (arrayRow2[i] == 4) {
four++;
}
if (arrayRow2[i] == 5) {
five++;
}
if (arrayRow2[i] == 6) {
six++;
}
if (arrayRow2[i] == 7) {
seven++;
}
if (arrayRow2[i] == 8) {
eight++;
}
if (arrayRow2[i] == 9) {
nine++;
}
}
for (int i = 0; i < size; i++) { //checks row 1
if (arrayRow3[i] == 1) { //checks if row one contains the value 1 in any position
one++;
}
if (arrayRow3[i] == 2) {
two++;
}
if (arrayRow3[i] == 3) {
three++;
}
if (arrayRow3[i] == 4) {
four++;
}
if (arrayRow3[i] == 5) {
five++;
}
if (arrayRow3[i] == 6) {
six++;
}
if (arrayRow3[i] == 7) {
seven++;
}
if (arrayRow3[i] == 8) {
eight++;
}
if (arrayRow3[i] == 9) {
nine++;
}
}
if (one == 1 && two == 1 && three == 1 && four == 1 && five == 1 && six == 1 && seven == 1 && eight == 1 && nine == 1) { // checks that every variable counting the repition of numbers 1-9 in the arrays is equal to one
isUnique = true;
cout << "True";
}
if (one != 1 || two != 1 || three != 1 || four != 1 || five != 1 || six != 1 || seven != 1 || eight != 1 || nine != 1) {
isUnique = false;
cout << "False";
}
return isUnique;
}
bool checkRowSum(int arrayrow1[], int arrayrow2[], int arrayrow3[], int size)
{
bool magicSquare = true; //variable declares whether it is a magic square or not
int sumRow1 = 0; //sum of row1
int sumRow2 = 0; //sum of row2
int sumRow3 = 0; //sum of row3
for (int i = 0; i < size; i++) {
sumRow1 += arrayrow1[i];
}
for (int i = 0; i < size; i++) {
sumRow2 += arrayrow2[i];
}
for (int i = 0; i < size; i++) {
sumRow3 += arrayrow3[i];
}
if (sumRow1 == 15 && sumRow2 == 15 && sumRow3 == 15) {
magicSquare = true;
cout << "true";
}
else {
magicSquare = false;
cout << "false";
}
return magicSquare;
}
bool checkColSum(int arrayrow1[], int arrayrow2[], int arrayrow3[], int size)
{
bool magicSquare = false;
int sumCol1 = 0;
int sumCol2 = 0;
int sumCol3 = 0;
for (int i = 0; i < size; i++) { //iterates through the array
if (i == 0) { //when i equals 1
sumCol1 += arrayrow1[i];
}
if (i == 1) {
sumCol2 += arrayrow2[i];
}
if (i == 2) {
sumCol3 += arrayrow3[i];
}
}
for (int i = 0; i < size; i++) {
if (i == 0) {
sumCol1 += arrayrow3[i];
}
if (i == 1) {
sumCol2 += arrayrow1[i];
}
if (i == 2) {
sumCol3 += arrayrow2[i];
}
}
for (int i = 0; i < size; i++) {
if (i == 0) {
sumCol1 += arrayrow2[i];
}
if (i == 1) {
sumCol2 += arrayrow3[i];
}
if (i == 2) {
sumCol3 += arrayrow1[i];
}
}
if (sumCol1 == 15 && sumCol2 == 15 && sumCol3 == 15) {
magicSquare = true;
cout << "true";
}
else {
magicSquare = false;
}
return magicSquare;
}
bool checkDiagSum(int arrayrow1[], int arrayrow2[], int arrayrow3[], int size)
{
bool magicSquare = true;
int sumDiag1 = 0;
int sumDiag2 = 0;
sumDiag1 = arrayrow1[0] + arrayrow2[1] + arrayrow3[2];
sumDiag2 = arrayrow1[3] + arrayrow2[1] + arrayrow3[0];
if (sumDiag1 == 15 && sumDiag2 == 15) {
magicSquare = true;
cout << "true";
}
else {
magicSquare = false;
cout << "false";
}
return magicSquare;
}
void fillArray(int arrayRow1[], int arrayRow2[], int arrayRow3[], int size)
{
int userInput;
//fills row 1
for (int i = 0; i < size; i++) { //iterates according to int size which is the number of columns/rows
cout << "Enter the number for row 1, column " << i+1 << ": ";
cin >> userInput;
arrayRow1[i] = userInput;
cout << endl;
}
//fills row 2
for (int i = 0; i < size; i++) {
cout << "Enter the number for row 2, column " << i+1 << ": ";
cin >> userInput;
arrayRow2[i] = userInput;
cout << endl;
}
//fills row 3
for (int i = 0; i < size; i++)
{
cout << "Enter the number for row 3, column " << i+1 << ": ";
cin >> userInput;
arrayRow3[i] = userInput;
cout << endl;
}
}
void showArray(int arrayrow1[], int arrayrow2[], int arrayrow3[], int size)
{
for (int i = 0; i < size; i++) { //displays row 1
cout << arrayrow1[i] << " ";
}
cout << endl; //moves down one row
for (int i = 0; i < size; i++) { //displays row 2
cout << arrayrow2[i] << " ";
}
cout << endl; //moves down one row
for (int i = 0; i < size; i++) { //displays row 3
cout << arrayrow3[i] << " ";
}
cout << endl; //moves down one row
}

8 Puzzle Code. Having Issues with my my queue not populating and i can not find the location of my bug

As the title states i'm having trouble finding the error with the way in which my queue is being populated. It should be holding every visited state node until they have been processed. but the queue is not being populated as it should be. Can anyone help me find the bug? Below is my implementation file for the PuzzleStateNode class and source.cpp
EDIT: After more debugging it would seem that the problem lies with the following chunk of code from the solvePuzzle function. The items are never pushed to my queue, and I don't understand why. Could it be an issue with my unordered_set?
void solvePuzzle(string stateArray[3][3]) {
ofstream oFile("output.txt");
PuzzleStateNode pState(stateArray);
queue<PuzzleStateNode> puzzleQueue;
unordered_set<string> visitedPuzzleStateSet;
if (pState.parityCheck() == true) {
puzzleQueue.push(pState);
for(int i = 0; i < 31; i++){
PuzzleStateNode myTempState(puzzleQueue.front());
//puzzleQueue.pop();
if (visitedPuzzleStateSet.find(myTempState.getPuzzleID()) == visitedPuzzleStateSet.end()) { // is our value in the set? if not then do the following
visitedPuzzleStateSet.emplace(myTempState.getPuzzleID()); // add to the list of visited states.
if (myTempState.getEmptyXArrayPos() == 0 || myTempState.getEmptyXArrayPos() == 1) { // if a move to the right is available
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareRight(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl << endl << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have visited this already" << endl;
system("pause");
}
}
END EDIT:
PuzzleStateNode.h
#pragma once
#include<queue>
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
class PuzzleStateNode
{
public:
PuzzleStateNode();
PuzzleStateNode(string tempArray[3][3]);
PuzzleStateNode(const PuzzleStateNode &other);
int getEmptyXArrayPos();
int getEmptyYArrayPos();
int getMoveCounter();
string getPuzzleID();
bool parityCheck();
bool checkForSolve();
void setPuzzleID();
void setEmptyXArrayPos(int x);
void setEmptyYArrayPos(int y);
void incrimentMoveCounter();
void pushToMoveQueue(string move);
void moveEmptySquareDown(int xEmptyPos, int yEmptyPos);
void moveEmptySquareUp(int xEmptyPos, int yEmptyPos);
void moveEmptySquareRight(int xEmptyPos, int yEmptyPos);
void moveEmptySquareLeft(int xEmptyPos, int yEmptyPos);
void printState(ofstream &oFile);
void printMoves(ofstream &oFile);
~PuzzleStateNode();
private:
string puzzleStateArray[3][3];
int moveCounter;
queue<string> moveQueue;
int emptyXArrayPos;
int emptyYArrayPos;
string puzzleID;
};
PuzzleStateNode.cpp
#include "PuzzleStateNode.h"
using namespace std;
PuzzleStateNode::PuzzleStateNode()
{
}
PuzzleStateNode::PuzzleStateNode(string tempArray[3][3])
{
puzzleID = "";
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
puzzleStateArray[i][j] = tempArray[i][j];
puzzleID += tempArray[i][j];
if (puzzleStateArray[i][j] == "E") {
emptyXArrayPos = j;
emptyYArrayPos = i;
}
}
}
moveCounter = 0;
moveQueue.push("The following lists the movement of the Empty or 'E' square until the puzzle is solved: ");
}
PuzzleStateNode::PuzzleStateNode(const PuzzleStateNode &other) {
{ puzzleID = "";
moveCounter = other.moveCounter;
moveQueue = other.moveQueue;
emptyXArrayPos = other.emptyXArrayPos;
emptyYArrayPos = other.emptyYArrayPos;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
puzzleStateArray[i][j] = other.puzzleStateArray[i][j];
puzzleID += other.puzzleStateArray[i][j];
}
}
}
}
int PuzzleStateNode::getEmptyXArrayPos() {
return emptyXArrayPos;
}
int PuzzleStateNode::getEmptyYArrayPos() {
return emptyYArrayPos;
}
int PuzzleStateNode::getMoveCounter() {
return moveCounter;
}
string PuzzleStateNode::getPuzzleID() {
return puzzleID;
}
bool PuzzleStateNode::checkForSolve() {
if (puzzleStateArray[0][0] == "1" && puzzleStateArray[0][1] == "2" && puzzleStateArray[0][2] == "3" && puzzleStateArray[1][0] == "4" && puzzleStateArray[1][1] == "5" && puzzleStateArray[1][2] == "6" && puzzleStateArray[2][0] == "7" && puzzleStateArray[2][1] == "8" && puzzleStateArray[2][2] == "E") {
return true;
}
return false;
}
void PuzzleStateNode::setPuzzleID() {
puzzleID = "";
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
puzzleID += puzzleStateArray[i][j];
}
}
}
void PuzzleStateNode::setEmptyXArrayPos(int x) {
emptyXArrayPos = x;
}
void PuzzleStateNode::setEmptyYArrayPos(int y) {
emptyXArrayPos = y;
}
void PuzzleStateNode::incrimentMoveCounter() {
moveCounter++;
}
void PuzzleStateNode::pushToMoveQueue(string move) {
moveQueue.push(move);
}
void PuzzleStateNode::printMoves(ofstream &oFile) {
string tempString;
for (int i = 0; i < moveQueue.size(); i++) {
cout << moveQueue.front() << endl;
moveQueue.push(moveQueue.front());
moveQueue.pop();
}
cout << endl << endl;
}
void PuzzleStateNode::printState(ofstream &oFile) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << puzzleStateArray[i][j];
}
cout << endl;
}
cout << endl;
}
void PuzzleStateNode::moveEmptySquareDown(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos + 1][xEmptyPos];
puzzleStateArray[yEmptyPos + 1][xEmptyPos] = "E";
moveQueue.push("Down");
moveCounter++;
cout << "Moving Down" << endl;
emptyYArrayPos = yEmptyPos + 1;
}
void PuzzleStateNode::moveEmptySquareUp(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos - 1][xEmptyPos];
puzzleStateArray[yEmptyPos - 1][xEmptyPos] = "E";
moveQueue.push("Up");
moveCounter++;
cout << "Moving Up" << endl;
emptyYArrayPos = yEmptyPos - 1;
}
void PuzzleStateNode::moveEmptySquareLeft(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos][xEmptyPos - 1];
puzzleStateArray[yEmptyPos][xEmptyPos - 1] = "E";
moveQueue.push("Left");
moveCounter++;
cout << "Moving Left" << endl;
emptyXArrayPos = xEmptyPos - 1;
}
void PuzzleStateNode::moveEmptySquareRight(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos][xEmptyPos + 1];
puzzleStateArray[yEmptyPos][xEmptyPos + 1] = "E";
moveQueue.push("Right");
moveCounter++;
cout << "Moving Right" << endl;
emptyXArrayPos = xEmptyPos + 1;
}
bool PuzzleStateNode::parityCheck() // counts number of swaps for a bubble sort excluding swaps involving the empty space
{
enter code here
// Puzzles with odd swaps have odd parity and are unsolvable.
string parityCheckString = "";
char tempChar;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
parityCheckString += puzzleStateArray[i][j];
}
}
int counter = 0;
for (int j = 0; j < 8; j++) {
for (int i = 0; i < 8; i++) {
if (parityCheckString[i] > parityCheckString[i + 1]) {
if (parityCheckString[i] == 'E') {
tempChar = parityCheckString[i];
parityCheckString[i] = parityCheckString[i + 1];
parityCheckString[i + 1] = tempChar;
}
else {
tempChar = parityCheckString[i];
parityCheckString[i] = parityCheckString[i + 1];
parityCheckString[i + 1] = tempChar;
counter += 1;
}
}
}
}
if (counter % 2 == 0) {
cout << "Even Parity, solving the 8 puzzle!" << endl;
return true;
}
else {
cout << "Parity is odd and puzzle is unsolvable. Skipping to next Puzzle." << endl;
return false;
}
}
PuzzleStateNode::~PuzzleStateNode()
{
}
source.cpp
#include"PuzzleStateNode.h"
#include<string>
#include<fstream>
#include<iostream>
#include<unordered_set>
using namespace std;
int main() {
void solvePuzzle(string stateArray[3][3]);
ifstream inFile("input.txt");
ofstream outFile("output.txt");
string puzNum;
int numberOfPuzzles;
string junk;
getline(inFile, puzNum); // read number of puzzles
numberOfPuzzles = stoi(puzNum); // convert value to int.
for (int i = 0; i < numberOfPuzzles; i++) {
string stateArray[3][3]; // populates a temporary puzzle state.
string temp;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
while (temp != "1" && temp != "2" && temp != "3" && temp != "4" && temp != "5" && temp != "6" && temp != "7" && temp != "8" && temp != "E") {
temp = inFile.get();
}
stateArray[i][j] = temp;
temp = inFile.get();
}
}
solvePuzzle(stateArray);
}
system("pause");
return 0;
}
void solvePuzzle(string stateArray[3][3]) {
ofstream oFile("output.txt");
PuzzleStateNode pState(stateArray);
queue<PuzzleStateNode> puzzleQueue;
unordered_set<string> visitedPuzzleStateSet;
if (pState.parityCheck() == true) {
puzzleQueue.push(pState);
for(int i = 0; i < 31; i++){
PuzzleStateNode myTempState(puzzleQueue.front());
//puzzleQueue.pop();
if (visitedPuzzleStateSet.find(myTempState.getPuzzleID()) == visitedPuzzleStateSet.end()) { // is our value in the set? if not then do the following
visitedPuzzleStateSet.emplace(myTempState.getPuzzleID()); // add to the list of visited states.
if (myTempState.getEmptyXArrayPos() == 0 || myTempState.getEmptyXArrayPos() == 1) { // if a move to the right is available
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareRight(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl << endl << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have visited this already" << endl;
system("pause");
}
}
if (myTempState.getEmptyXArrayPos() == 1 || myTempState.getEmptyXArrayPos() == 2) {
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareLeft(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
tempState.incrimentMoveCounter();
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have visited this state" << endl;
system("pause");
}
}
if (myTempState.getEmptyYArrayPos() == 0 || myTempState.getEmptyYArrayPos() == 1) {
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareDown(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have this state already" << endl;
system("pause");
}
}
if (myTempState.getEmptyYArrayPos() == 1 || myTempState.getEmptyYArrayPos() == 2) {
PuzzleStateNode tempState(myTempState);
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareUp(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "have visited this state already" << endl;
system("pause");
}
}
}
}
}
else
oFile.close();
return;
}
I found the problem! I was never resetting puzzle id's after copying so all puzzle states had the same ID for my set.

Having issues converting numbers into roman numerals

for class I have to create a code so that it could ask the user for an integer between 1-99 and be able to print that integer in roman numerals. Issue is after creating my code it would only print the numbers fully up to 39. Once it hits 40 it give's no Roman Numeral output and then from 41-99 it wont print the tenth place value(Ex. 45 will come out as V). Here's my code at the moment.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num;
int tenum;
int remnum;
string romnum;
string fromnum;
cout << "Enter a number between 1 and 99. \n";
cin >> num;
tenum = num / 10;
remnum = num % 10;
if (tenum == 9)
{
fromnum == "XC";
}
else if (tenum == 8)
{
fromnum == "LXXX";
}
else if (tenum == 7)
{
fromnum == "LXX";
}
else if (tenum == 6)
{
fromnum == "LX";
}
else if (tenum == 5)
{
fromnum == "L";
}
else if (tenum == 4)
{
fromnum == "XL";
}
else if (tenum == 3)
{
fromnum = "XXX";
}
else if (tenum == 2)
{
fromnum == "XX";
}
else if (tenum == 1)
{
fromnum == "X";
}
if (remnum == 9)
{
romnum = "IX";
}
else if (remnum == 8)
{
romnum = "VIII";
}
else if (remnum == 7)
{
romnum = "VII";
}
else if (remnum == 6)
{
romnum = "VI";
}
else if (remnum == 5)
{
romnum = "V";
}
else if (remnum == 4)
{
romnum = "IV";
}
else if (remnum == 3)
{
romnum = "III";
}
else if (remnum == 2)
{
romnum = "II";
}
else if (remnum == 1)
{
romnum = "I";
}
cout << tenum << endl;
cout << remnum << endl;
cout << fromnum;
cout << romnum << endl;
return 0;
}
You've mixed up == and =
change lines like
fromnum == "XL"
to
fromnum = "XL"
Demo
(I used a switch statement for brevity)
same answer with: Converting integer to Roman Numeral
#include <iostream>
#include <string>
std::string to_roman(int value)
{
struct romandata_t { int value; char const* numeral; };
static romandata_t const romandata[] =
{ 1000, "M",
900, "CM",
500, "D",
400, "CD",
100, "C",
90, "XC",
50, "L",
40, "XL",
10, "X",
9, "IX",
5, "V",
4, "IV",
1, "I",
0, NULL }; // end marker
std::string result;
for (romandata_t const* current = romandata; current->value > 0; ++current)
{
while (value >= current->value)
{
result += current->numeral;
value -= current->value;
}
}
return result;
}
int main()
{
for (int i = 1; i <= 4000; ++i)
{
std::cout << to_roman(i) << std::endl;
}
}
this code converts up to 1000. just take what you need and you are good to go!
from http://rosettacode.org/wiki/Roman_numerals/Encode#C.2B.2B

Error C2440, Battleship C++

My compiler is telling me that I have an error, but I've e-mailed my instructor and he says my code is perfectly fine.
The error is Error:
1 error C4716: 'ShipPlacement' : must return a value, line 139
I'm unsure as to where I went wrong exactly so I'm going to share my code for ShipPlacement:
ShipPlacement(Coord grid[10][10])
{
CoordAndBearing SetBowAndDirection();
CoordAndBearing cab;
cab = SetBowAndDirection();
int start;
if((cab.dir == 3) || (cab.dir == 1)) // GOING HORIZONTAL //
{
if (cab.dir == 3)
start = cab.bx;
else
start = cab.bx - 4;
for(int i = start; i <= start + 4; i = i + 1)
{
grid[i][cab.by].isShip = true;
}
}
else // GOING VERTICAL
{
if(cab.dir == 0)
start = cab.by;
else
start = cab.by - 4;
for (int i = start; i <=start + 4; i = i + 1)
{
grid[cab.bx][i].isShip = true;
}
}
}
And here is my int main:
int main()
{
srand((unsigned int) time (NULL));
void ShipPlacement(Coord grid[10][10]);
Coord grid[10][10];
SetGridParameters(grid);
ShipPlacement(grid);
int ammo = 18;
int hits = 0;
while (hits < 5 && ammo >0 )
{
int x;
int y;
DisplayGrid(grid);
cout << "Ammo left = " << ammo << endl;
cout << "Enter Coord: " << endl;
cin >> x >> y;
ammo= ammo - 1;
if (grid [x][y].isShip == true)
{
hits = hits + 1;
}
else
{
cout << " You missed... " << endl;
}
}
DisplayGrid(grid);
if(hits == 5 )
{
cout << "You sunk the U.S.S McCall!!";
}
else
{
cout << " You lost ";
}
system("pause");
return 0;
}
You've defined the ShipPlacement function without a return type. Some (most?) compilers will issue a warning stating they're assuming it returns an int, followed by an error since it doesn't.
Just explicitly define it as "returning" void (i.e., void ShipPlacement(Coord grid[10][10])), and you should be fine.