C++ Array Troubles - c++

Im trying to build a tic tac toe game, and for some reason seem to be getting hit by a bug when I try and put a value into any values, it seems to give the selected character(say its player 1, and thus an 'X'), into the values selected by the user(where he wants it to be) but also annoyingly into [1][2] and [2][0] of the array. The code is attached.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace System;
using namespace std;
string game_board[2][2];
bool exit_condition = false;
int x_coords;
int y_coords;
int current_player;
string cp_char;
int returnxwin();
int returnowin();
int main()
{
cout << "Welcome to Tic-Tac-Toe Console!\n" << endl;
//Start of game
while(exit_condition != true){
cout << "This is the game board: " << endl;
cout << " - | 1 | 2 | 3 | " << endl;
cout << " 1 | " << game_board[0][0] <<" | " <<game_board[1][0] << " | " << game_board[2][0] << " | " <<endl;
cout << " 2 | " << game_board[0][1] <<" | " <<game_board[1][1] << " | " << game_board[2][1] << " | "<<endl;
cout << " 3 | " << game_board[0][2] <<" | " <<game_board[1][2] << " | " << game_board[2][2] << " | \n"<<endl;
//TESTING PURPOSES BE SURE TO REMOVE!
current_player = 1;
//Says which player is first
cout << "Player " << current_player << " is first!" << endl;
//Determines which player is first, and if so, which character to give to them.
if(current_player == 1)
{
cp_char = "X";
} else if(current_player == 2)
{
cp_char = "Y";
}
bool valid_input = false;
while(valid_input != true){
cout << "Where would you like to place your " << cp_char << " ? (X co-ordinates(top row))\n" ;
cin >> x_coords;
cout << "Where would you like to place your " << cp_char << " ? (Y co-ordinates(side row))\n" ;
cin >> y_coords;
if((x_coords <= 3) && (y_coords <=3))
{
if(game_board[x_coords-1][y_coords-1] == "")
{
game_board[1][2] = "";
game_board[2][0] = "";
//Problem Here!
game_board[x_coords-1][y_coords-1] = cp_char;
break;
valid_input = true;
}
else
{
cout << "Invalid Input! Somebody has already taken the slot!" << endl;
}
}
else
{
cout << "Invalid input! Please enter a number from 1 to 3" << endl;
}
}
//End of Valid Input Loop
//make sure to remove break;
// break;
}
system("pause");
return 0;
}
I haven't finished the game yet, but was at a loss as to why this is happening :s
On another side note, Im also looking for a way to randomly decide whether player 1 or 2 goes first.
Edit: I tried doing [3][3], as suggested but it still gives me an error. Ideas?

game_board is defined as an array of 2x2 strings, should it be 3x3?
string game_board[3][3]
I guess you are going over the array so you get undefined results..
Regarding having a way to randomly choose which player will start just use the rand() function:
srand(time(NULL)); // to initialize the random sequence
current_player = rand()%2 + 1; //player will be either 1 or 2

string game_board[2][2];
This allocates a game board 2 entries wide by 2 entries tall. That's one smaller than a USTTTA / IOCTTT - sanctioned tournament game board. Try this:
std::string game_board[3][3];

Related

C++ Left Center Right Dice Game (Game Loop and connecting vectors/arrays to classes/header files)

So i have to code the dice game LCR for a final prject but am having some trouble. First off, I know the code is sloppy and really redundant, that's why im looking for help. I couldn't figure out how to connect the 'chips' int vector and 'name' array into the player.h file. I basically need help writing methods for the chip passing to make the code less redundant. But another problem of mine is having the game loop until just one person has chips. Thanks for any help or advice.
LeftCenterRight.cpp
#include <iostream>
#include <string>
#include <time.h>
#include "Dice.h"
#include "Player.h"
#include <vector>
#include <algorithm>
using namespace std;
void Player::gameRules()
{
cout << ("\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n\n");
cout << ("Left Center Right is a multiplayer dice game");
cout << ("With a minimum of three players.");
cout << ("Dice containing letters L, C, R along\n"
"with dots on the remaining side are rolled each turn");
cout << ("\n-----Each Player starts with three chips-----\n");
cout << (">> For each L rolled, the player must pass one chip to the player to their left\n"
">> For each R rolled, the player must pass one chip to the player to their right\n"
">> For each C rolled, the player must pass a chip into the center pot (out of play)\n"
">> Dots are neutral and require no action");
cout << ("If a player has three or more chips, he/she rolls all three dice\n"
"If a player only has two chips, he/she rolles onlt two dice\n"
"If a player only has one chip, he/she rolls only one die\n"
"If a player is out of chips, he/she is still in the game,\n"
"\tbut does not roll any dice and passes their turn"
"\n\n >>> The last player with chips is the winner <<<");
cout << ("\n\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n");
};
int main()
{
int result = 0;
int currPlayer = 1;
srand((unsigned)time(NULL));
int numPlayers;
cout << "How many players are playing? (Please enter 3 or more): " << endl;
cin >> numPlayers;
if (numPlayers <= 2)
{
while (numPlayers <= 2)
{
cout << "More players needed.";
cout << "How many players are player?: ";
cin >> numPlayers;
}
}
std::string* names = new string[numPlayers]; // getting names and index is seat number
for (int i = 0; i < numPlayers; i++)
{
cout << "Please enter your name player " << i+1 << endl;
cin >> names[i];
std::string playerName = names[i];
}
vector<int>chips[1]; // intial 3 chips
for (int i = 0; i < numPlayers; i++)
{
int InitialChips = 3;
chips->push_back(InitialChips);
}
Player::gameRules();
int sum = 0;
for (int i = 0; i < chips->size(); i++)
{
int num = chips->at(i);
sum+=num;
}
int thePot = 0;
int i = 0;
while (sum > 0)
{
if ( i >=4 )
{
i = 0;
}
string currPlayer = names[i];
int currSeat = i;
cout << "It's " << currPlayer << "'s Turn!" << endl;
cout << "[1] Roll Dice [2] Quit :";
int choice;
cin >> choice;
if (choice == 1)
{
if (chips->at(currSeat) == 0)
{
break;
}
if (chips->at(currSeat) >= 3)
{
for (int k = 0; k <= 3; k++)
{
int outcome = Dice::rollDice();
if (outcome == 1)
{
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
if (i == 0)
{
int j = (numPlayers - 1);
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
else
{
int j = i - 1;
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
}
if (outcome == 2)
{
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
if (i == chips->size())
{
int j = chips->at(0);
int currChips2 = chips->at(0);
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
else
{
int j = i + 1;
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
}
if (outcome == 3)
{
thePot++;
cout << ">> +1 chip to the Center Pot" << endl;
cout << "There are now " << thePot << " chip(s) in the Center Pot " << endl;
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
break;
}
else if ((outcome == 4) || (outcome == 5) || (outcome == 6))
{
break;
}
}
}
// ^^basically copied and pasted most of the while loop for the other two numbers of dice to roll^^
// had redundant code for if the player had 2 chips, to roll two dice only ^^
// also redundant code for only one chip, to roll one die. ^^
}
}
else if (choice == 2)
{
break;
}
else
{
cout << ">> Input Error";
cout << "[1] Roll Dice [2] Quit";
cin >> choice;
}
i++;
}
return 0;
}
Dice.h
#pragma once
using namespace std;
class Dice
{
public:
static int rollDice();
static int diceOutcome;
};
int Dice::rollDice()
{
int diceOutcome;
diceOutcome = (rand() % 6) + 1;
switch (diceOutcome)
{
default:
cout << "Error, retry";
case 1:
if (diceOutcome == 1)
{
cout << " --- " << endl;
cout << "You rolled a | L | Move 1 chip left." << endl;
cout << " --- " << endl;
return 1;
}
break;
case 2:
if (diceOutcome == 2)
{
cout << " --- " << endl;
cout << "You rolled a | R | Move 1 chip right." << endl;
cout << " --- " << endl;
return 2;
}
break;
case 3:
if (diceOutcome == 3)
{
cout << " --- " << endl;
cout << "You rolled a | C | Move 1 chip to the center." << endl;
cout << " --- " << endl;
return 3;
}
break;
case 4:
if (diceOutcome == 4)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
case 5:
if (diceOutcome == 5)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
case 6:
if (diceOutcome == 6)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
}
}
To be fair, I'm quite new to programming, but I have been working on this project for days and kept running into conatiner problems and storing the name and chip values independently. So i've tried a lot of different things, probably not correctly though so I'm open to anything.

How do I stop segmentation error with array in C++?

I am creating a simple command line, tic-tac-toe game in C++. Whenever I reun the code I get no compiler errors but then VSCode tells me once I have given input that there is a Segmentation Fault. I will paste my code below:
#include <iostream>
#include <cmath>
using namespace std;
void print_board(string board[3][3])
{
cout << " | | " << endl;
cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << " " << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << " " << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << " " << endl;
cout << " | | " << endl;
}
string turn(string board[3][3], bool xturn)
{
int position;
cout << "Where would you like to go (1 - 9): ";
cin >> position;
if (xturn)
{
string player_turn = "X";
}
else
{
string player_turn = "O";
}
board[(int)floor(position / 3)][(position % 3) - 1] = "X";
return board[3][3];
}
int main(void)
{
string board[3][3] = {{" ", " ", " "}, {" ", " ", " "}, {" ", " ", " "}};
bool xturn = true;
while (true)
{
print_board(board);
board[3][3] = turn(board, xturn);
xturn = !xturn;
}
return 0;
}
Any help is much is much appreciated. Thanks! If it helps I am using the GCC compiler.
void print_board(string board[3][3])
why are you using a string[3][3] ? you basically just need a 3x3 character array
board[(int)floor(position / 3)][(position % 3) - 1] = "X";
make sure you keep yourself in range 0..2, -1 is outside and will
cause undefined behavior
return board[3][3];
No that is wrong in more ways than one, and in any case there is no need to return a copy
board[3][3] = turn(board, xturn);
this will not go well, you return a board of 3x3 strings but assign
it to at best, an undefined place.
since you already pass the address of the board to your turn function, that is that is all needed. change it in place.
turn(board, xturn);
arrays are addresses in memory, it is the starting address where in memory some data is stored
if you pass an array/matrix to a function you are letting the function know where in memory it is stored, so any changes to the array/matrix will be done in place, therefore you do not need to return a copy.

How do I display a list of previous guesses before a user guesses a new number, using an array?

I am creating a guessing game. I need to display the users' previous guesses every time the user makes another guess. I am using an array and pointers. The code below only displays the most recent thing entered by the user. I need it to display a list of previous inputs. The part of the code that includes the pointer seems to be where my issue is located, but I don't know exactly where?
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
void arrayTable(int[]);
int reviewGuess(int Answer, int userGuess);
int _tmain(int argc, _TCHAR* argv[])
{
int guessNum = 3; // Declares how many guesses the user can take.
int userGuess = 0;
int Answer;
char Choice;
int *pointer = NULL;
srand(time(NULL));
Answer = rand() % 20 + 1; //Gives a random number ranging from 1 to 20
do{
int x;
cout << " ____________________________________________________\n";
cout << " | |\n";
cout << " | I want to play a game |\n"; // Displays a welcome message
cout << " | I am thinking of a number between 1 through 20. |\n";
cout << " | Can you guess the number in less than " << guessNum << " tries ? |\n";
cout << " | Press '1' to play. |\n";
cout << " | Press '2' if you want to EXIT!!! |\n";
cout << " |__________________________________________________|\n";
cin >> x;
switch (x)
{
case 1:
for (int i = 0; i < guessNum; i++) //Counter, for loop, stops when condition is met.
{
cout << " This is guess# " << i + 1 << " : "; //Takes the user input
cin >> userGuess;
int guessNum = 1;
pointer = new int[guessNum];
for (int i = 0; i < guessNum; i++) //Store the user guesses
{
*(pointer + i) = userGuess;
}
cout << "Here is a list of your guesses" << endl;
for (int i = 0; i < guessNum; i++) // Display the user guesses.
{
cout << " Guess# " << i + 1 << " is " << *(pointer + i) << endl;
}
reviewGuess(Answer, userGuess); //Calls the function
}
cout << " ------------------> <----------------------\n";
cout << " ------------------> You Lost!!! <----------------------\n";
cout << " ------------------> <----------------------\n";
cout << " You have exceeded the amount of guesses you were given.\n";
cout << " The correct Answer is : " << Answer << endl;
break;
case 2:
cout << "-------------->Thank You.\n";
cout << "-------------->Have a good day.\n";
break;
system("pause");
return 0;
}
cout << "would you like to play again (y/n)?";
cin >> Choice;
} while (Choice == 'y');
system("pause");
return 0;
}
int reviewGuess(int Answer, int userGuess)
{
if (userGuess != Answer)
{
if (userGuess > Answer)
cout << " -----> 1 \n";
else
cout << " -----> -1 \n";
}
else
{
cout << " -----> 0 \n";
cout << " Good JOb, you have guessed the right number. \n";
system("pause");
return 0;
}
}
review the changes, and don't just copy and paste.
to access pointer array members, you can use the index [].
you are already in a for loop, so you dont want to create another for loop getting input, that would be 3 x 3 requests for data.
you were storing the data into an int, not into the array you created with pointer.
pointer isn't a very good name, when its an array of guesses. try calling it something more readable.
once it ran, if the user won, it still triggered losing code. you need to break out before accessing that code the way you have it set up. i created a bool, and changed your reviewguess method to return a bool whether they won or not. break out on exiting. note the double use of breaks; its in a for loop in a switch. you have to break out of the foor loop, and then break out of the switch. you cannot just put it after the for loop, as it will then keep asking for input if they win, and then report they won at the end.
note the use of the global constant to keep track of how many guesses. you were declaring and initializing the same variables all over the place. initialize with the type keyword once, at the start, and if you need the variable in the loop, initalize it before the loop so you dont try to reinitialize every iteration.
logic was reversed as far as higher or lower with reviewGuess
Not a bad start, keep your head up, and i hope i could help you out!
this is my first time answering a question.
Code:
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
void arrayTable(int[]);
bool reviewGuess(int, int);
int _tmain(int argc, _TCHAR* argv[])
{
const int MAX_NUMBER_GUESSES = 3;// Declares how many guesses the user can take.
int currentGuessNum = 0;
int userGuess = 1;
int Answer;
char Choice;
int x;
int *arrGuesses = NULL;
bool gameWon = false;
srand(time(NULL));
//Gives a random number ranging from 1 to 20
do {
Answer = rand() % 20 + 1; //Gives a random number ranging from 1 to 20
//you want this in the loop otherwise you always have same answer
cout << " ____________________________________________________\n";
cout << " | |\n";
cout << " | I want to play a game |\n"; // Displays a welcome message
cout << " | I am thinking of a number between 1 through 20. |\n";
cout << " | Can you guess the number in less than " << MAX_NUMBER_GUESSES << " tries ? |\n";
cout << " | Press '1' to play. |\n";
cout << " | Press '2' if you want to EXIT!!! |\n";
cout << " |__________________________________________________|\n";
cin >> x;
switch (x)
{
case 1:
userGuess = 1;
arrGuesses = new int[MAX_NUMBER_GUESSES];
for (int i = 0; i < MAX_NUMBER_GUESSES; i++) //Counter, for loop, stops when condition is met.
{
cout << " This is guess# " << userGuess << " : " << endl; //Takes the user input
cin >> arrGuesses[i];
cout << "Here is a list of your guesses" << endl;
for (int i = 0; i < userGuess; i++) // Display the user guesses.
{
cout << " Guess# " << i+1 << " is " << arrGuesses[i] << endl;
}
gameWon = reviewGuess(Answer, arrGuesses[i]); //Calls the function
if (gameWon)
{
break;
}
userGuess++;
}
if (gameWon)
{
break;
}
cout << " ------------------> <----------------------\n";
cout << " ------------------> You Lost!!! <----------------------\n";
cout << " ------------------> <----------------------\n";
cout << " You have exceeded the amount of guesses you were given.\n";
cout << " The correct Answer is : " << Answer << endl;
break;
case 2:
cout << "-------------->Thank You.\n";
cout << "-------------->Have a good day.\n";
break;
system("pause");
return 0;
}
cout << "would you like to play again (y/n)?";
cin >> Choice;
} while (Choice == 'y');
system("pause");
return 0;
}
bool reviewGuess(int Answer, int userGuess)
{
if (userGuess != Answer)
{
if (userGuess < Answer)
cout << " -----> 1 \n";
else
cout << " -1 <----- \n";
return false;
}
else
{
cout << " -----> 0 \n";
cout << " Good JOb, you have guessed the right number. \n";
system("pause");
return true;
}
}

C++ error C2181: illegal else without matching if

I'm new to C++. I have been following an online course that teaches you how to make a Hangman game in C++. For the most part the code was working, every time I debugged it ran fine. I completed the entire code and double checked it, but I'm getting an error on one of the 'else' the errors I'm getting is "error C2181: illegal else without matching if.
Here's my code.
// Hangman game
// CN
// Header file
#include "stdafx.h"
// Input/Output
#include <iostream>
// Text
#include <string>
// Information storage
#include <vector>
// Figuring out the information storage
#include <algorithm>
// Converts lower cased letters to higher case letters
#include <cctype>
// Reads computers time and distributes a word from a list accordingly
#include <ctime>
// Library for system
#include <cstdlib>
using namespace std;
int main()
{
// Constant data type which is a fixed value, MaxWrong in Pascal Text and the max number of guesses.
const int MaxWrong = 6;
vector<string> words;
words.push_back("SANTA CLAUSE");
words.push_back("REINDEER");
words.push_back("PRESENT");
words.push_back("TREE");
words.push_back("MILK");
words.push_back("COOKIE");
// Parenthesis must always match
srand(static_cast<unsigned int>(time(0)));
random_shuffle(words.begin(), words.end());
const string theWord = words[0];
int wrong = 0;
string soFar(theWord.size(), '_');
string used = "";
cout << "\n******** Welcome to Chaye's Hangman ********\n\n";
cout << " __ \n";
cout << " | | \n";
cout << " | \n";
cout << " | \n";
cout << " | \n";
cout << " | \n";
cout << " ___|____ \n\n";
cout << " Do Your Best Human \n\n";
// Loop
while ((wrong < MaxWrong) && (soFar != theWord))
{
cout << "\n You have " << (MaxWrong - wrong);
cout << " incorrect tries left.\n";
cout << "\n You've used these letters:\n" << used << endl;
char guess;
cout << "\n\n Enter your guess: ";
cin >> guess;
guess = toupper(guess);
while (used.find(guess) != string::npos)
{
cout << "\n You've already tried " << guess << endl;
cout << " Enter your guess: ";
cin >> guess;
guess = toupper(guess);
}
used += guess;
if (theWord.find(guess) != string::npos)
{
cout << " That's right " << guess << " is in the word,\n";
for (int i = 0; i < theWord.length(); ++i)
{
if (theWord[i] == guess)
{
soFar[i] = guess;
}
}
}
else
{
cout << " sorry. " << guess << " isn't in the word.\n";
++wrong;
}
// If one is wrong
if (wrong == 1)
{
cout << " __ \n";
cout << " | | \n";
cout << " | O \n";
cout << " | \n";
cout << " | \n";
cout << " | \n";
cout << " ___|____ \n\n";
cout << " Do Your Best Human \n\n";
}
else
{
cout << endl;
}
// If one is wrong
if (wrong == 2)
{
cout << " ___ \n";
cout << " | | \n";
cout << " | O \n";
cout << " | # \n";
cout << " | \n";
cout << " | \n";
cout << " ___|____ \n\n";
cout << " Do Your Best Human \n\n";
}
else
{
cout << endl;
}
// If one is wrong
if (wrong == 3)
{
cout << " ___ \n";
cout << " | | \n";
cout << " | O \n";
cout << " | /# \n";
cout << " | \n";
cout << " | \n";
cout << " ___|____ \n\n";
cout << " Do Your Best Human \n\n";
}
else
{
cout << endl;
}
// If one is wrong
if (wrong == 4)
{
cout << " ___ \n";
cout << " | | \n";
cout << " | O \n";
cout << " | /#\ \n";
cout << " | \n";
cout << " | \n";
cout << " ___|____ \n\n";
cout << " Do Your Best Human \n\n";
}
else
{
cout << endl;
}
// If one is wrong
if (wrong == 5)
{
cout << "\n You've been hung \n";
cout << " ___ \n";
cout << " | | \n";
cout << " | O \n";
cout << " | /#\ \n";
cout << " | / \n";
cout << " | \n";
cout << " ___|____ \n\n";
cout << " Do Your Best Human \n\n";
}
else
{
cout << "\n I'm suprised you've got this far\n";
}
cout << "\n The word was " << theWord << endl;
}
// If one is wrong
if (wrong == MaxWrong)
{
cout << "\n You've been hung \n";
cout << " ___ \n";
cout << " | | \n";
cout << " | O \n";
cout << " | /#\ \n";
cout << " | / \ \n";
cout << " | \n";
cout << " ___|____ \n\n";
cout << " Do Your Best Human \n\n";
}
else
{
cout << "\n I'm suprised you've got this far\n";
}
cout << "\n The word was " << theWord << endl;
// Pause Console
system("pause");
// Kills the application once done
return 0;
}
There should be no semicolon in this line:
if (theWord.find(guess) != string::npos);
this semicolon terminates the whole if statement and the following {...} block is executed unconditionally. Following else is therefore no longer matched with the if statement.
And you are also missing closing ) bracket in your while statement:
while (used.find(guess) != string::npos
{
...
}
Change
** else **
to
else
Your compiler is interpreting that as an operator. If it still fails, edit your post w/ the error. Also worth noting, if you compile w/ the -g flag you get some debug output which can be beneficial.

program crashes at CIN input | C++

so i made a DOS program however my game always crashes on my second time running to the cin function.
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
//call functions
int create_enemyHP (int a);
int create_enemyAtk (int a);
int find_Enemy(int a);
int create_enemyDef (int a);
// user information
int userHP = 100;
int userAtk = 10;
int userDef = 5;
string userName;
//enemy Information
int enemyHP;
int enemyAtk;
int enemyDef;
string enemies[] = {"Raider", "Bandit", "Mugger"};
int sizeOfEnemies = sizeof(enemies) / sizeof(int);
string currentEnemy;
int chooseEnemy;
// ACTIONS
int journey;
int test;
int main()
{
// main menu
cout << "welcome brave knight, what is your name? " ;
cin >> userName;
cout << "welcome " << userName << " to Darland" << endl;
//TRAVELING
MENU:
cout << "where would you like to travel? " << endl;
cout << endl << " 1.> Theives Pass " << endl;
cout << " 2.> Humble Town " << endl;
cout << " 3.> Mission HQ " << endl;
cin >> journey;
if (journey == 1)
{
// action variable;
string c_action;
cout << "beware your journey grows dangerous " << endl;
//begins battle
// Creating the enemy, HP ATK DEF AND TYPE. ;
srand(time(0));
enemyHP = create_enemyHP(userHP);
enemyAtk = create_enemyAtk(userAtk);
enemyDef = create_enemyDef(userDef);
chooseEnemy = find_Enemy(sizeOfEnemies);
currentEnemy = enemies[chooseEnemy];
cout << " Here comes a " << currentEnemy << endl;
cout << "stats: " << endl;
cout << "HP :" << enemyHP << endl;
cout << "Attack : " << enemyAtk << endl;
cout << "Defense : " << enemyDef << endl;
ACTIONS:
cout << "Attack <A> | Defend <D> | Items <I>";
cin >> c_action;
//if ATTACK/DEFEND/ITEMS choice
if (c_action == "A" || c_action == "a"){
enemyHP = enemyHP - userAtk;
cout << " you attack the enemy reducing his health to " << enemyHP << endl;
userHP = userHP - enemyAtk;
cout << "however he lashes back causing you to have " << userHP << "health left " << endl;
//end of ATTACK ACTION
}
the last line "cin >> c_action crashes. i use two other pages. they just create the functions. is it a complier issue. also why does my complier always shutdown after it runs he app. is there a way to stop it?
A few hints:
I never use forward declarations of functions ( such as "int create_enemyHP (int a);" ) if I can avoid them. If you do this then there are two places in your code that must be correct for your program to work. It makes life easier if there is always a "single source of truth"
Have you run this code through the debugger? It will help you find problems much more quickly.
If your c_action variable is only intended to be a char, I'd suggest to use a char variable, rather than a string.
You might want to try this way, and if you're still faced with an error, you might give
scanf("%c", &c_action); //assuming you used a char.
I didn't understand if the program crashes before you type the "action" or after. Because if it crashes before, then I think your problems are caused by white spaces characters in the input buffer.