Segmentation fault: 11 c++ Error - c++

this is my first time asking a question on this forum so here it goes. I am creating a tic-tac-toe game for practice and am using enumerators and recursion because I have never really done enumeration and could always get some recursion practice in. Well anyway I just finished coding for the player2 to take a random move and after about 3 turns it gives a segmentation fault and I cannot figure out why... I hope you guys can figure it out and thank you!
#include <iostream>
#include <string>
#include <cstdlib>
const int size = 3;
enum play {none,X,O};
void NPC(play (&board)[size][size],play player2) {
srand(time(NULL));
int tempx = rand() % 3;
int tempy = rand() % 3;
if(board[tempx][tempy] == none)
board[tempx][tempy] = player2;
else
NPC(board,player2);
}
void getBoardState(play (&board)[size][size],int y,int x) {
if(board[x][y] == none) std::cout << " ";
else if(board[x][y] == X) std::cout << "X";
else std::cout << "O";
}
void printboard(play (&board)[size][size]){
int length = 4 * size - 1;
for(int i = 1; i <= length; i++) {
for(int j = 1; j <= length; j++) {
if(i % 4 == 0 && j % 4 == 0) std::cout << "+";
else if(i % 4 == 0) std::cout << "-";
else if(j % 4 == 0) std::cout << "|";
else if(i % 2 == 0 && j % 2 == 0) getBoardState(board,(i - 2)/4,(j - 2)/4);
else std::cout << " ";
}
std::cout << std::endl;
}
}
int main() {
play player = O, player2 = X;
bool over = false;
play board[size][size];
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
board[i][j] = none;
}
}
std::string player1 = "";
std::cout << "What would You like to be? An X or an O?" << std::endl;
while(((player1 != "X") + (player1 != "O")) == 2) {
std::cin >> player1;
if(((player1 != "X") + (player1 != "O")) == 2)
std::cout << "Invalid entry! Please enter X or an 0!" << std::endl;
}
if(player1 == "X") {
player2 = O;
player = X;}
int tempx,tempy;
while(!over) {
std::cout << "Please enter an x and then a y (1 to " << size << ")" << std::endl;
std::cin >> tempx;
std::cin >> tempy;
while(tempx > size || tempy > size || board[tempx-1][tempy-1] != none) {
std::cout << "Invalid entry! Try again!" << std::endl;
std::cin >> tempx;
std::cin >> tempy;
}
board[tempx-1][tempy-1] = player;
NPC(board,player2);
printboard(board);
}
return 0;
}

You're running out of stack space in your recursion because you call srand(time(NULL)) every time. The random number generator should only be seeded once, in main, and not in NPC. time(NULL) returns a number of seconds, so it changes infrequently (compared to how fast your recursive function calls will occur) which will consume all available stack space.

Related

How do I remove comma after last number/output loop in C++

My Code:
#include <iostream>
using namespace std;
void result(int test)
{
for (int num = 1; num <= test; num++)
{
if (num % 3 == 0 && num % 5 == 0)
cout << "extra";
else if (num % 3 == 0 )
cout << "love ";
else if(num %5 == 0)
cout << "extraextra";
else
cout << num;
cout << ",";
}
}
int main()
{
int test = 100;
result(test);
return 0;
}
My Output:
1,2,love ,4,extraextra,love ,7,8,love ,extraextra,11,love ,13,14,extra,16,17,love ,19,extraextra,love ,22,23,love ,extraextra,26,love ,28,29,extra,31,32,love ,34,extraextra,love ,37,38,love ,extraextra,41,love ,43,44,extra,46,47,love ,49,extraextra,love ,52,53,love ,extraextra,56,love ,58,59,extra,61,62,love ,64,extraextra,love ,67,68,love ,extraextra,71,love ,73,74,extra,76,77,love ,79,extraextra,love ,82,83,love ,extraextra,86,love ,88,89,extra,91,92,love ,94,extraextra,love ,97,98,love ,extraextra,
My question:
How to delete only the very last comma?
Add a condition for the last value of num. The full code would be:
#include <iostream>
using namespace std;
void result(int test)
{
for (int num = 1; num <= test; num++)
{
if (num % 3 == 0 && num % 5 == 0)
cout << "extra";
else if (num % 3 == 0 )
cout << "love ";
else if(num %5 == 0)
cout << "extraextra";
else
cout << num;
if(num < test) cout << ","; // Here you add the condition
}
cout << endl; // Allows for flushing the output (Thanks #bruno)
}
int main()
{
int test = 100;
result(test);
return 0;
}
In case you really do not like the additional test of num visible in
for (int num = 1; num <= test; num++)
{
if (num % 3 == 0 && num % 5 == 0)
cout << "extra";
else if (num % 3 == 0 )
cout << "love ";
else if(num %5 == 0)
cout << "extraextra";
else
cout << num;
if (num < test)
cout << ',';
}
and
for (int num = 1; num <= test; num++)
{
if (num != 1)
cout << ',';
if (num % 3 == 0 && num % 5 == 0)
cout << "extra";
else if (num % 3 == 0 )
cout << "love ";
else if(num %5 == 0)
cout << "extraextra";
else
cout << num;
}
you can avoid that explicit test doing :
const char * sep = "";
for (int num = 1; num <= test; num++)
{
cout << sep;
sep = ",";
if (num % 3 == 0 && num % 5 == 0)
cout << "extra";
else if (num % 3 == 0 )
cout << "love ";
else if(num %5 == 0)
cout << "extraextra";
else
cout << num;
}
but probably this is less readable and a (very) little more expensive at the execution
Your loop runs for the last time at num == test, so just print commas for num less than test or num not equal to test.
i.e. simply replace cout << ","; with:
if(num < test) cout << ",";
or
if(num != test) cout << ",";
After having read all the suggestion and the constructive critics, I modified my answer in the following way:
#include <iostream>
using namespace std;
void singlecheck(int num){
if (num % 3 == 0 && num % 5 == 0)
cout << "extra";
else if (num % 3 == 0 )
cout << "love ";
else if(num %5 == 0)
cout << "extraextra";
else
cout << num;
}
void result(int test)
{
if(test>0){
for (int num = 1; num <test; num++){
singlecheck(num);
cout << ", ";
}
singlecheck(test);
cout << endl;
}
}
int main()
{
int test = 15;
result(test);
return 0;
}
I added one more function, which is doing the "test" job, while the cycle is done in another function. Now the result is correct also with input 0: I added one if at the beginning. In this way, only one if-check has to be done instead of a total of test if-checks, which was my principal concern. Previous version has repeated code which is not a good programming practice.

Multidimensional array not changing elements from function for some reason

The function player_attack() changes the elements of the multi-dimensional array pc_board but when i reprint it in main, the array prints unchanged.
I removed all unnecessary code.
I tried to pass is at as a parameter to the function but i got an error for using a multidimensional array in the parameter.
$
bool game_won = false;
string board[5][5];
string pc_board[5][5];
void initialize_player_board() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
board[i][j] = "-";
}
}
}
void print_map() {
for (int i = 0; i < 5; i++) {
cout << setw(5);
cout << i << setw(5);
for (int j = 0; j < 5; j++) {
cout << board[i][j] << setw(5);
}
cout << setw(10);
for (int j = 0; j < 5; j++) {
cout << pc_board[i][j] << setw(5);
}
cout << endl;
}
}
void pc_add_battleship() {
int x = 0;
int y = 0;
int choice_generator = 0;
char choice;
x = rand() % 4 + 1;
y = rand() % 4 + 1;
choice_generator = rand() % 2;
if (choice_generator == 0) {
choice = 'h';
}
else {
choice = 'v';
}
if (choice == 'h') {
pc_board[y - 1][x] = 'O';
pc_board[y][x] = 'O';
pc_board[y + 1][x] = 'O';
}
if (choice == 'v') {
pc_board[y][x - 1] = 'O';
pc_board[y][x] = 'O';
pc_board[y][x + 1] = 'O';
}
}
void player_attack() {
int x = 0;
int y = 0;
cout << "Choose an x coordinate to attack: " << endl;
cin >> x;
cout << "Choose a y coordinate to attack: " << endl;
cin >> y;
if (pc_board[y][x] == "O") {
cout << "HIT!" << endl;
pc_board[y][x] == "H";
}
else {
cout << "Miss." << endl;
pc_board[y][x] == "M";
}
}
int main()
{
srand(time(0));
initialize_player_board();
initialize_pc_board();
cout << "Welcome to the battleship game." << endl;
print_map();
Add_battleship();
pc_add_battleship();
while (!game_won) {
print_map();
player_attack();
}
return 0;
}
$
I expected for the multidimensional array to change its elements due to the function
In your function player_attack you use wrong operator:
if (pc_board[y][x] == "O") {
cout << "HIT!" << endl;
pc_board[y][x] == "H"; // here
}
else {
cout << "Miss." << endl;
pc_board[y][x] == "M"; // and here
}
instead of == that is a comparison operator you should use = that is the assignment operator.
Using operator == in this context is still valid C++ syntax, which produces a boolean value, however it does not modify the arguments (which are left and right side of comparison), which is probably what you want to do in most cases. Enabling compiler flags like -Wall or Wextra along with Werror helps to avoid this kind of bugs.

C++ a function call is not called again after the loop iterates

Hey so I am relatively a beginner at programming. I am trying to create a very simple minesweeper game over a 2D array, the issue I am running into is after the player steps on a mine (game over) they are given the option to play again. After this the set difficulty function is supposed to be called a second time (since it is within the loop) and a new minefield is to be generate. Unfortunately none of that is happening and the program skips that process.
Here is my code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int choose_difficulty(int x);
int generator();
int main()
{
//create initial variables
string Ans;
int Rounds;
int NewPosition_x = 0;
int NewPosition_y = 0;
//ask user if he wants to run the program and expect input
cout << "Would you like to play a game? Y/N" << endl;
cin >> Ans;
//based on user input the program will run or not
if (Ans == "Y" || "y") {
while (Ans == "Y" || "y")
{
//Create position variables to be checked
int Position_x;
int Position_y;
//ask user how many rounds in the game they want
cout << "How many chances do you want to give yourself?" << endl;
cin >> Rounds;
//Generate minefield could not be done as separate function since you cannot output an array
int a = choose_difficulty(a);
int mines;
int n,m;
srand (time (0));
if(a == 0) {
mines = 3;
n = 4;
m = n;
}
else if (a == 1){
mines = 5;
n = 4;
m = n;
}
else if (a == 2){
mines = 7;
n = 4;
m = n;
}
int minefield[n][m] = { };
int g, h;
for (int num = 0; num < mines; num++) {
g = rand()%n;
h = rand()%n;
minefield[g][h] = 1;
}
for (int x = 0; x < Rounds; x++)
{
//Begin Game
cout << "Where are you at to avoid the mines? (Enter a 2 numbers 0 through 3)" << endl;
cin >> NewPosition_x >> NewPosition_y;
//check if the player has entered a new position
while (NewPosition_x == Position_x && NewPosition_y == Position_y) {
cout << "You have to move somewhere, put a valid location" << endl;
cin >> NewPosition_x >> NewPosition_y;
}
//check to see if that position is valid
while ((NewPosition_x < 0 || NewPosition_x > 3) || (NewPosition_y < 0 || NewPosition_y > 3)) {
cout << "I'm sorry, but that place doesn't exist. Try somewhere else" << endl;
cin >> NewPosition_x >> NewPosition_y;
}
//Assign Player Position and check position vs mines
Position_x = NewPosition_x;
Position_y = NewPosition_y;
if (minefield[Position_y][Position_x] == 1) {
cout << "You stepped on a mine, Game Over" << endl;
cout << "You minefield was this:" << endl;
for (int i=0; i < n; i++){
for (int j=0; j < n; j++){
cout << minefield[i][j] << "\t";
}
cout << endl;
}
cout << "Would you like to play again? Y/N" << endl;
cin >> Ans;
if (Ans == "n" || Ans == "N"){
return 0;
}
}
else if ((minefield[Position_x + 1][Position_y] == 1) || (minefield[Position_x - 1][Position_y] == 1) || (minefield[Position_x][Position_y + 1] == 1) || (minefield[Position_x][Position_y - 1] == 1)) {
cout << "You're hot right now, you better watch your step. Continue to the next round" << endl;
}
else {
cout << "You're safe. Continue to the next round" << endl;
}
}
}
}
return 0;
}
int choose_difficulty(int a)
{
do{
string difficulty;
//Difficulty Selection
cout << "Choose the game difficulty: Easy, Medium, Hard" << endl;
cin >> difficulty;
if (difficulty == "easy" || difficulty == "Easy"){
a = 0;
}
else if (difficulty == "medium" || difficulty == "Medium"){
a = 1;
}
else if (difficulty == "hard" || difficulty == "Hard"){
a = 2;
}
else {
cout << "Invalid input";
a = 3;
}
}while (a == 3);
return a;
}
You should be careful on this kind of error:
//based on user input the program will run or not
if (Ans == "Y" || "y") {
while (Ans == "Y" || "y")
{
This, above, will always be true being "y" different from 0 (false).
Instead you need to check that Ans is either equal to "Y" or "y" in this way:
//based on user input the program will run or not
if (Ans == "Y" || Ans == "y") {
while (Ans == "Y" || Ans == "y")
{
Or use, as suggested in the comments, std::toupper()
UPDATE
It seems you have a problem on your buffer you should use cin.ignore() in order to clean it;

Dynamic array error in Conways Game of Life

I am working on a program that emulates conways game of life, and it works perfectly with the preset dimensions. However, once i try to use the dynamic dimensions as seen in option e, i start having problems. The main problem is in the "life" function which iterates throughout the array and decides if it should bring to life a cell. I have been debugging for a while and it i enter the dimensions as 50*40, it iterates until 61, 1. This should technically work but it just breaks everytime. Keep in mind that I add 12 to each dimension to account for the buffer zone I put around the edges. Technically it should work then right? If you have any suggestions I would really appreciate it!
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <new> // i havent used this one yet
#include <cmath>
using namespace std;
// REMEMBER: The outside of the array is 6 more than what we show so that nothing interferes
//also that it goes y,x and that x is going to be bigger so that we get a rectange
//we use the copy function to copy an array from eachother, either the current one to the temp one or
//vise versa. This is so that we can alter the cells one step at a time without affecting everything else.
void copy(int **array1, int **array2, int o, int p)
{
for(int j = 0; j < o; j++)
{
for(int i = 0; i < p; i++)
array2[j][i] = array1[j][i];
}
} // the second array sent is assigned the first array sent!
//this array will initialize our arrays so that we can use them later
int** init(int n, int m)
{
int **array;
array = new int*[m]; // x
array = new int*[n]; // y
for (int q=0; q < n; q++)
{
array[q] = new int[n];
for (int w=0; w < m; w++)
{
array[w] = new int[m];
}
}
return array;
}
void populate(int o, int p, int** board){ // THIS FUNCTION HASN'T BEEN USED YET
for(int i=0; i < p; i++)
{
for(int j=0; j < o; j++) // It was in a in-class demo but i dont think i need it
{
board[i][j] = pow(i, j);
}
}
}
//The life function looks at the pieces around the cell and figures out what happens next.
// Probably the most important in the entire program, feast your eyes!
void life(int **array, int o, int p)
{
//Copies the main array to a temp array so changes can be made without affecting anyone else
int **temp;
temp = init(o, p);
copy(array, temp, o, p);
for(int j = 1; j < o; j++)
{
for(int i = 1; i < p; i++)
{
// checks all 8 cells surrounding it
int count = 0;
cout << " j is " << j << " and i is " << i << endl;
// cout << array[j][i]; // DEBUGGING
count =
array[j-1][i] + array[j-1][i-1] +
array[j][i-1] + array[j+1][i-1] +
array[j+1][i] + array[j+1][i+1] +
array[j][i+1] + array[j-1][i+1];
//cell dies.
if(count < 2 || count > 3)
{
temp[j][i] = 0;
}
//nothing happens.
if(count == 2)
{
temp[j][i] = array[j][i];
}
//now the cell will be born, or if it already is alive then it stays that way.
if(count == 3)
{
temp[j][i] = 1;
}
}
}
//Copies the temp array back to the main array.
copy(temp, array, o, p);
}
//This function prints the 40 x 50 part of the array, a 1 means that there will be a cell there,
//otherwise it will just be an empty space.
void print(int **array, int o, int p)
{
// WE ONLY CHECK WHAT WE SEE, WHICH IS 6 LESS THAN THE ARRAY!!!
for(int j = 6; (j < (o-6)); j++)
{
for(int i = 6; (i < (p-6)); i++)
{
if(array[j][i] == 1 )
cout << '*';
else
cout << '.';
}
cout << endl;
}
}
//I read somewhere it would be a good idea to make sure to end the program early if it somehow
//became stable by itself early. so this compares the old array with the new one to check if they
//are the same. This commonly occurs if a glider runs off the screen for example.
bool compare(int **array1, int **array2,int o,int p)
{
int counter = 0;
for(int j = 0; j < o; j++)
{
for(int i = 0; i < p; i++)
{
if(array1[j][i]==array2[j][i])
counter++;
}
}
if(counter == o*p)
return true;
else
return false;
}
int main()
{
int o= 52, p=62;
int **firstgen;
int **next;
int **backup;
// 40 + 12, 50 + 12
int x, y;
char starty;
char again;
char cont;
bool comparison;
//Here is where we initialize our arrays
firstgen = init(o,p);
next = init(o,p);
backup = init(o,p);
cout << endl << "Welcome to John Conway's Game of Life." << endl;
//This loop is for if we are still simulating, don't get confused!
do
{
//this loop checks for inputs.
do
{
menu: //this is a goto we use for if we change dimensions
x = 0, y = 0;
//now we get the menu
cout << endl << "--- Choose an option Below ---" << endl;
cout << "(a) Glider" << endl;
cout << "(b) Gosper Gilder gun" << endl;
cout << "(c) R Pentomino Pattern" << endl;
cout << "(d) Oscillator" << endl;
cout << "(e) Change the dimensions (it defaults to (50*40)" << endl;
cin >> starty;
}while(starty != 'a' && starty != 'b' && starty != 'c' && starty != 'd' && starty != 'e');
int i = 0;
//we need to assign firstgen in this area
//choose a glider position
if (starty == 'a'){
x= 0, y= 0;
cout << " X dimension: ";
cin >> x;
cout << " Y dimension: ";
cin >> y;
if (x < 0 || x > p || y < 0 || y > o){
cout << endl << "you entered invalid dimensions" << endl;
goto menu;
}
x = x+6; //we add 6 because there are six spots to the left that aren't shown we need to account for
y = y+6;
//creates the glider
firstgen[y][x] = 1;
firstgen[y][x+1] = 1;
firstgen[y][x+2] = 1;
firstgen[y-1][x] = 1;
firstgen[y-2][x+1] = 1;
}
else if (starty == 'b'){
x= 0, y= 0;
cout << "Your dimensions are based on the farthest left point" << endl;
cout << " X dimension: ";
cin >> x;
cout << " Y dimension: ";
cin >> y;
if (x < 0 || x > p || y < 0 || y > o){
cout << endl << "you entered invalid dimensions" << endl;
goto menu;
}
//this is because we have the buffer zone of 6
x = x+6;
y = y+6;
//Gosper gun
//box on left
firstgen[y][x] = 1;
firstgen[y][x+1] = 1;
firstgen[y+1][x] = 1;
firstgen[y+1][x+1] = 1;
//left circle starting in top of the left curve (flat part)
firstgen[y][x+10] = 1;
firstgen[y-1][x+11] = 1;
firstgen[y-2][x+12] = 1;
firstgen[y-2][x+13] = 1;
firstgen[y+1][x+10] = 1;
firstgen[y+2][x+10] = 1;
firstgen[y+3][x+11] = 1;
firstgen[y+4][x+12] = 1;
firstgen[y+4][x+13] = 1;
//dot in middle
firstgen[y+1][x+14] = 1;
//arrow thing on the right
firstgen[y-1][x+15] = 1;
firstgen[y][x+16] = 1;
firstgen[y+1][x+16] = 1;
firstgen[y+1][x+17] = 1;
firstgen[y+2][x+16] = 1;
firstgen[y+3][x+15] = 1;
//boomerang bit on the far right section
firstgen[y][x+20] = 1;
firstgen[y][x+21] = 1;
firstgen[y-1][x+20] = 1;
firstgen[y-1][x+21] = 1;
firstgen[y-2][x+20] = 1;
firstgen[y-2][x+21] = 1;
firstgen[y-3][x+22] = 1;
firstgen[y-3][x+24] = 1;
firstgen[y-4][x+24] = 1;
firstgen[y+1][x+22] = 1;
firstgen[y+1][x+24] = 1;
firstgen[y+2][x+24] = 1;
//tiny box on farthest right, almost done!
firstgen[y-1][x+34] = 1;
firstgen[y-1][x+35] = 1;
firstgen[y-2][x+34] = 1;
firstgen[y-2][x+35] = 1;
}
else if (starty == 'c')
{
x= 0, y= 0;
cout << "Your dimensions are based on the farthest left point" << endl;
cout << " X dimension: ";
cin >> x;
cout << " Y dimension: ";
cin >> y;
if (x < 0 || x > p || y < 0 || y > o){
cout << endl << "you entered invalid dimensions" << endl;
goto menu;
}
x = x+6;
y = y+6;
//creates R Pentamino pattern
firstgen[y][x] = 1;
firstgen[y][x+1] = 1;
firstgen[y+1][x+1] = 1;
firstgen[y-1][x+1] = 1;
firstgen[y-1][x+2] = 1;
}
// creates the simple oscillator
else if (starty == 'd')
{
x= 0, y= 0;
cout << "Your dimensions are based on the top of the oscillator" << endl;
cout << " X dimension: ";
cin >> x;
cout << " Y dimension: ";
cin >> y;
if (x < 0 || x > p || y < 0 || y > o){
cout << endl << "you entered invalid dimensions" << endl;
goto menu;
}
x = x+6;
y = y+6;
firstgen[y][x] = 1;
firstgen[y+1][x] = 1;
firstgen[y+2][x] = 1;
}
// allows you to choose your dimensions
else if (starty == 'e')
{
o= 0, p= 0;
x= 0, y= 0;
cout << "choose the height and width of your field, between 0 and 100" << endl;
cout << " X dimension: ";
cin >> x;
cout << " Y dimension: ";
cin >> y;
if (x < 0 || x > 100 || y < 0 || y > 100){
cout << endl << "Please keep dimensions between 0 and 100" << endl;
goto menu;
}
// the problem is that it is adding my x dimension and my placement choice together and then
// starts to run the program, which threadbreaks. I need to find out why these two values are
// adding together and fix it
x = x+12;
y = y+12; // plus twelve so that we have 6 around all sides
p = x;
o = y;
firstgen = init(o,p);
next = init(o,p);
backup = init(o,p);
// is this part below necessary?
//firstgen[o][p];
// next[o][p];
// backup[o][p];
// idk
// cout << "y value is: " << o << " and the x value is " << p << endl; // debugging
goto menu;
}
//Loop that does the simulation.
do
{
//Prints the generation. If i == 0, the firstgen array is copied to the
//next array, and is printed before any functions act upon it.
cout << endl << "Generation " << i << ":" << endl << endl;
//Initializes the arrays by copying the firstgen array to the next array.
if(i == 0)
copy(firstgen, next, o, p);
//this stuff below happens in every cycle
cout << "the x/p value is" << p << "and the y/o value is " << o << endl;
copy(next, backup, o, p);
print(next, o, p);
life(next, o, p);
i++;
//Pauses the system .2 seconds so that it doesn't flash past you super fast and you
// can't appreciate its beauty
system("sleep .2");
//Checks whether the generation is a multiple of 100 to ask
//the user if they want to continue
if(i % 100 == 1 && i != 1)
{
cout << endl;
//Loop to check for proper inputs.
do
{
cout << "Continue? (y or n): ";
cin >> cont;
}while(cont != 'y' && cont != 'n');
if(cont == 'n')
break;
}
//Compares the current generation with a backup generation.
//The idea is that if it is the same with the backup generation then
//something boring is going on or smething went wrong. It will end if that
//is the case.
comparison = compare(next, backup, o, p);
if(comparison == false)
// system("clear");
//cout << string( 10, '\n' );
if(comparison == true)
cout << endl;
}while(comparison == false);
//Loop to check if we want to keep going.
do
{
cout << "Run another Simulation? (y or n): ";
cin >> again;
}
while(again != 'y' && again != 'n');
//this is where we clean out all our firstgen values
//i used to have this at the top but didn't really need it
for(int y = 0; y < o; y++)
{
for(int x = 0; x < p; x++)
{
firstgen[y][x] = 0;
}
}
}
while(again == 'y');
return 0;
}
I figured it out!
The thing to take away from this is to make sure that your initiation function creates the array with the same size as the one you will be accessing. I was trying to get values from array[52][1] which didn't exist because in my init function i only had the for loop running while n < o, which means it didn't create the 52nd row. what a relief!

Strange first element of array after reading in from file

I'm reading in a sodoku board from a text file. The board is represented by 9 rows of 9 digit numbers, like this:
594632817
123478569
678159234
215346798
346897125
789215346
437561982
851924673
962783451
EDIT
Here are the results when I change the while condition to (input >> char):
Output as chars are read in:
96212486
71931369
48728254
35185947
67350
Output of printArray:
962124867
193136948
728254351
859476735
�$%w��
����QȿȔ
L�`g�Pw
���w�
And here's the output for while (!input.eof()):
�94632817
123478569
678159234
215346798
346897125
789215346
437561982
851924673
962783451
END EDIT
The trouble is, when I place each digit into a multidimensional array, the element at [0][0] appears as a shaded question mark (compiled with g++). The problem only surfaces when I'm printing out the contents of the array, the data as it's read in appears to be fine. For what it's work, this also happens if I cout << board[0][0] from the main function.
Any help would be appreciated!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int createArray(string filename);
bool checkRows(char board[][9]);
bool checkColumns(char board[][9]);
bool checkBoxes(char board[][9]);
void printArray(char board[][9]);
int main ()
{
char board [9][9];
int i = 0;
int j = 0;
int count = 0;
ifstream input("board.txt");
char ch;
while (input >> ch)
{
// ch = input.get();
if (ch != '\n')
{
cout << ch;
board[i][j] = ch;
j++;
if (j % 9 == 0)
{
i++;
}
}
if (j > 8)
j = 0;
if (i > 8)
i = 0;
count++;
if (count % 10 == 0)
cout << endl;
}
input.close();
printArray(board);
cout << checkRows(board) << endl;
cout << checkColumns(board) << endl;
return 0;
}
void printArray(char board[][9])
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
cout << board[i][j];
}
cout << endl;
}
cout << board[0][0] << endl;
cout << board[0][1] << endl;
}
By doing this, reading ch two times.
Remove ch = input.get(); and you will read each number correctly.
while (input >> ch)
{
ch = input.get();
...
}
Again, consider changing condition below to make sure correct endl placement
if (count % 10 == 0)
cout << endl;
to
if (count % 9 == 0)
cout << endl;