I'm writing some game at c++. The problem is with arrays. It always shows the 'desk' with points (empty parts). Need comments are in the code:
void showDesk(int someArray[][3])
{
for(int i = 0; i < 3 ;i++)
{
for (int j = 0; j < 3; j++)
{
if(someArray [i][j] == 0) cout << ".";
else if (someArray[i][j] == 1) cout << "x";
else if (someArray[i][j] == 2) cout << "o";
}
cout<<"\n";
}
}
void newDesk (int someArray[][3])
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
someArray [i][j] = 0;
}
bool empty(int someArray[][3], int x, int y)
{
if (someArray[x][y] == 0)
return true; // It returns true
else
return false;
}
void setMark(int someArray[][3],int x,int y,int mark)
{
if (empty(someArray,x,y))
someArray [x][y] == mark; // But this never calls!
}
int main(int argc, char** argv) {
int x,y;
int mark;
int someArray [3][3];
newDesk(someArray);
showDesk(someArray);
cout << "------------------\n";
while (true)
{
cout<< "put x,y\n";
cin >> x>>y;
cout << "put mark\n";
cin >> mark;
setMark(someArray,x,y,mark);
showDesk(someArray);
}
return 0;
}
== is comparison, = is assignment.
Your line:
someArray [x][y] == mark;
Does nothing. It should be:
someArray [x][y] = mark;
someArray [x][y] == mark tests the array to see if its equal to mark, but never actually sets it to anything...
Related
I am coding a Conway's Game of Life.My task is reading from file.txt to array of strings.And then using this array as the input array of the game. I have written a code about it. But it is full of error. I don't know what is the correct way to do this.
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
using namespace std;
namespace gamearray {
int main()
ifstream file_("file.txt");
if(file.is_open())
{
string myArray[10];
for(int i = 0; i < 10; ++i)
{
for(int i = 0; i < 10; i++)
file >> array1[j][i];
}
}
return 0;
}
void copy(int array1[10][10], int array2[10][10])
{
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
array2[j][i] = array1[j][i];
}
}
void life(int array[10][10], char choice)
{
int temp[10][10];
copy(array, temp);
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
if(choice == 'm')
{
int count = 0;
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];
if(count < 2 || count > 3)
temp[j][i] = 0;
if(count == 2)
temp[j][i] = array[j][i];
if(count == 3)
temp[j][i] = 1;
}
}
}
copy(temp, array);
}
bool compare(int array1[10][10], int array2[10][10])
{
int count = 0;
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
if(array1[j][i]==array2[j][i])
count++;
}
}
if(count == 10*10)
return true;
else
return false;
}
void print(int array[10][10])
{
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
if(array[j][i] == 1)
cout << '*';
else
cout << ' ';
}
cout << endl;
}
}
int main()
{gamearray::main();
int gen0[10][10];
int todo[10][10];
int backup[10][10];
char neighborhood;
char again;
char cont;
bool comparison;
{do
{
do
{
cout << "Which neighborhood would you like to use (m): ";
cin >> neighborhood;
}while(neighborhood != 'm');
system("CLS");
int i = 0;
do
{
srand(time(NULL));
for(int j = 0; j < 10; j++)
{
for (int i = 0; i < 10; i++)
gen0[j][i] = rand() % 2;
}
if(i == 0)
copy(gen0, todo);
copy(todo, backup);
print(todo);
life(todo, neighborhood);
i++;
system("sleep .5");
if(i % 10 == 1 && i != 1)
{
cout << endl;
do
{
cout << "Would you like to continue this simulation? (y/n): ";
cin >> cont;
}while(cont != 'y' && cont != 'n');
if(cont == 'n')
break;
}
comparison = compare(todo, backup);
if(comparison == false)
system("CLS");
if(comparison == true)
cout << endl;
}while(comparison == false);
do
{
cout << "Would you like to run another simulation? (y/n): ";
cin >> again;
}while(again != 'y' && again != 'n');
}while(again == 'y');
return 0;
}
}
/*
* spielm.cpp
*
* Created on: 22.09.2016
* Author: fislam
*/
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
void GetFile();
bool MakeArray();
char ChgArray();
//char GameBoard();
const int ROW1 =10;
const int COL1 =10;
const int BOARD_ROWS(10);
const int BOARD_COLS(10);
ifstream myfile;
string filename;
char live = 'X';
char dead = '.';
char board [BOARD_ROWS][BOARD_COLS];
int main()
{
int q;
//GetFile();
if ( MakeArray() ){
for ( int i(0); i <10; i++)
ChgArray();
}
else {
cout << "Error parsing input file" << endl;
}
cin >> q;
return 0;
}
void GetFile()
{
cout<<"Enter the filename: \n";
cin>>filename;
return;
}
bool MakeArray()
{
bool ret(false);
char val;
int totCnt = BOARD_ROWS*BOARD_COLS;
myfile.open (/*filename.c_str()*/"c_str.txt");
if ( myfile.is_open() ) {
for (int r=0; r<ROW1; r++)
{
for (int c=0; c<COL1; c++)
{
myfile>>val;
if ( val == dead || val == live ) {
board[r-1][c-1] = val;
totCnt--;
}
}
}
if ( !totCnt ) {
ret = true;
}
myfile.close();
}
return ret;
}
char getNextState(char b[BOARD_ROWS][BOARD_COLS], int r, int c)
{
char ret;
return ret;
}
char ChgArray()
{
char boardTmp[BOARD_ROWS][BOARD_COLS];
for (int r=0; r<BOARD_ROWS; r++)
{
for (int c=0; c<BOARD_COLS; c++)
{
boardTmp[r][c] = getNextState(board,r,c);
cout << boardTmp[r][c];
}
cout<<endl;
}
memcpy(board,boardTmp,sizeof(board));
cout << endl;
}
Instead of the previous I wrote new. and it worked
aftert main you are missing {
in first and second loop you have i loop twice
why do you need to copy ?
you can use this function fscanf() to read your file
e.g.
File= fopen(FileName, "r");
if( File == NULL ){
printf("Impossible to open file %s ! \n",FileName);
}
if( File != NULL)
{
char text[255];
while(!feof(File))
{
fscanf(File,"%s\n",&text);
....
}
}
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
using namespace std;
const int MAX = 9;
typedef char BOARD[MAX][MAX];
void dis_board(BOARD);
void new_board(BOARD, ifstream& in);
void add();
void remove(BOARD);
bool chk_row(BOARD arr, int row, int col);
bool chk_col(BOARD arr, int row, int col);
bool chk_sqr(BOARD arr, int row, int col);
int main()
{
BOARD board;
int row=0, col=0, num_ele = 0, num;
char ch1;
ifstream infile;
infile.open("mp6in.txt");
infile.get(ch1);
while (infile)
{
if (ch1 == 'N')
new_board(board, infile);
if (chk_row == false)
cout << "There is an error" << endl;
if (chk_col == false)
cout << "There is an error" << endl;
chk_sqr(board, 0, 0);
if (chk_sqr == false)
cout << "There is an error" << endl;
if (ch1 == 'D')
dis_board(board);
infile.get(ch1);
}
}
void dis_board(BOARD arr)
{
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
cout << setw(3) << arr[i][j];
cout << endl;
}
cout << endl;
}
void new_board(BOARD arr, ifstream& in)
{
in.ignore(100, '\n');
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
in.get(arr[i][j]);
in.ignore(100, '\n');
}
}
bool chk_row(BOARD arr, int row, int col)
{
for (int i = 0; i < MAX; i++)
{
if (i != col)
{
if (arr[row][i] == arr[row][col])
{
return false;
}
}
}
return true;
}
bool chk_col(BOARD arr, int row, int col)
{
for (int i = 0; i < MAX; i++)
{
if (i != row)
{
if (arr[i][col] == arr[row][col])
{
return false;
}
}
}
return true;
}
bool chk_sqr(BOARD arr, int row, int col)
{
int asquare = row / 3;
int bsquare = col / 3;
for (int i = asquare * 3; i < (asquare * 3 + 3); i++)
{
for (int j = bsquare * 3; j < (bsquare * 3 + 3); j++)
{
if (!(i == row && j == col))
{
if (arr[row][col] == arr[i][j])
{
return false;
}
}
}
}
return true;
}
Just in case I'm talking to anyone besides myself. I tried implementing the following checking functions and of course they aren't working correctly. For instance I know my first board has a duplicate number in the lower right block but my function can't find it.
chk_row is a function - you need to call it. Currently you are just checking with:
if (chk_row == false)
This is just checking if the function pointer is false, which is never going to happen. You need to call the function like this:
if (chk_row(board, row, col) == false)
You will need to work out what row and col should be. Probably you need a loop to check all the rows and columns, but I figure this is homework, so you should try it yourself.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
This sudoku solving program is getting compiled but getting error "segmentation fault " please help me in solving this problem and clarify why i am getting segmentation error as i have written every thing properlu .thanks in advance
#include<iostream>
#include<math.h>
class sudoku
{
public:
sudoku();
void initializeSudokuGrid();
void printSudokuGrid();
bool solveSudoku();
bool findEmptyGridSlot(int &row, int &col);
bool canPlaceNum(int row, int col, int num);
bool numAlreadyInRow(int row, int num);
bool numAlreadyInCol(int col, int num);
bool numAlreadyInBox(int smallGridRow, int smallGridCol, int num);
int grid[9][9];
};
sudoku::sudoku()
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
grid[i][j] = 0;
}
}
std::cout << "\n all the grid locations are initialise to zero";
}
void sudoku::initializeSudokuGrid()
{
char x = 'y';
while (x == 'y')
{
int row, col, var;
std::cout
<< "\n enter the row,column and integer in the box(that is 1-9 numbers \n";
std::cin >> row;
std::cin >> col;
std::cin >> var;
grid[row][col] = var;
std::cout
<< "\n are there any slots that u want to enter the numbers into the boxs enter y else enter n \n";
std::cin >> x;
}
}
void sudoku::printSudokuGrid()
{
std::cout << "\n";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
std::cout << grid[i][j] << " ";
}
std::cout << "\n";
}
}
bool sudoku::solveSudoku()
{
int row, col;
if (findEmptyGridSlot(row, col))
{
for (int num = 1; num <= 9; num++)
{
if (canPlaceNum(row, col, num))
{
grid[row][col] = num;
if (solveSudoku()) //recursive call
return true;
grid[row][col] = 0;
}
}
return false; //backtrack
}
else
return true; //there are no empty slots
}
bool sudoku::numAlreadyInRow(int row, int num)
{
for (int i = 0; i < 9; i++)
{
if (num != 0 && grid[row][i] == num)
return true;
}
return false;
}
bool sudoku::numAlreadyInCol(int col, int num)
{
for (int i = 0; i < 9; i++)
{
if (num != 0 && grid[i][col] == num)
return true;
}
return false;
}
bool sudoku::canPlaceNum(int row, int col, int num)
{
if (!numAlreadyInRow(row, num))
{
if (!numAlreadyInCol(col, num))
{
int smallGridRow = row - row % 3;
int smallGridCol = col - col % 3;
if (!numAlreadyInBox(smallGridRow, smallGridCol, num))
{
return true;
}
}
}
return false;
}
bool sudoku::numAlreadyInBox(int smallGridRow, int smallGridCol, int num)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (grid[i + smallGridRow][j + smallGridCol] == num)
return true;
}
}
return false;
}
bool sudoku::findEmptyGridSlot(int &row, int &col)
{
for (int row = 0; row < 9; row++)
{
for (int col = 0; col < 9; col++)
{
if (grid[row][col] == 0)
return true;
}
}
return false;
}
int main()
{
sudoku s;
s.printSudokuGrid();
s.initializeSudokuGrid();
s.printSudokuGrid();
std::cout << "\n after solving the problem \n";
if (s.solveSudoku())
s.printSudokuGrid();
else
std::cout << "\n solution doesnt exist for this type of solution \n";
return 0;
}
There's a mistake in your findEmptyGridSlot function
bool sudoku::findEmptyGridSlot(int &row, int &col)
{
for(int row=0;row<9;row++)
{
for(int col=0;col<9;col++)
{
...
You're declaring new int variables row and col in the loops, but you probably meant to use the ones passed as parameters.
Remove the int keyword to use the parameters instead of declaring new variables:
for(row=0;row<9;row++)
{
for(col=0;col<9;col++)
{
It gives the following error:
error C2872: 'count' : ambiguous symbol
Count variable has been declared as a global variable and the code compiles and runs in Sublime Text. Don't understand why Visual Studio is crying over it.
#include <iostream>
#include <fstream>
using namespace std;
int** am; // Adjacency matrix
int* ar, * ar2; // Arrays to work with
int n; // Number of nodes
int node1, node2, k; // For reading input from the console
int count;
bool checkReachability(int, int, int);
void fillArray(int);
void updateArray(int,int);
void freeMemory();
int main() {
ifstream in;
in.open("Input2.txt");
int a, b;
if(in.is_open()) {
in >> n;
// Allocate memory on the heap dynamically for the adjacency matrix:
am = new int*[n];
ar = new int[n];
ar2 = new int[n];
for (int i = 0; i < n; i++) {
am[i] = new int[n];
}
// Initialize the values of the adjacency matrix with 0s and the principle diagonal with 1s initially:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
am[i][j] = 1;
} else {
am[i][j] = 0;
}
}
}
while(!in.eof()) {
in >> a >> b;
am[a-1][b-1] = 1;
}
cout << "The adjacency matrix input is as follows: \n\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << am[i][j] << " ";
}
cout << endl << endl;
}
in.close();
} else {
cout << "\nError reading the input file\n\n";
}
char c;
do {
cout << "\nPlease enter the input (node1, node2, k): \n";
cin >> node1 >> node2 >> k;
fillArray(node1-1);
count = 0;
if(checkReachability(node1-1,node2-1,k)) {
cout << "\nReachable within " << k << " steps";
if (count < k) {
cout << " (actually " << count << ")";
}
cout << endl << endl;
} else {
cout << "\nNot reachable within " << k << " steps \n";
}
cout << "\nDo you want to continue? Y/N \n\n";
cin >> c;
} while (c == 'Y' || c == 'y');
freeMemory();
system("pause");
return 0;
}
bool checkReachability(int n1, int n2, int k) {
if (n1 == n2) return true;
count++;
if (count <= k) {
if (ar[n2] != 0) return true;
int x;
for (int i = 0; i < n; i++) {
if (ar[i] != 0 && i != n1) {
ar[i]++;
x = ar[i];
}
}
for(int i = 0; i < n; i++) {
ar2[i] = ar[i];
}
for(int i = 0; i < n; i++) {
if (ar2[i] == x) {
fillArray(i);
updateArray(x,i);
if (checkReachability(ar2[i], n2, k)) return true;
}
}
}
return false;
}
void fillArray(int x) {
// To fill the array with the adjacencies of a particular node
for(int i = 0; i < n; i++) {
ar[i] = am[x][i];
}
}
void updateArray(int x, int y) {
for(int i = 0; i < n; i++) {
if (ar[i] == 1 && i != y) {
ar[i] = x;
}
}
}
void freeMemory() {
// To free the dynamically allocated memory on the heap
for (int i = 0; i < n; i++) {
delete [] am[i];
}
delete [] ar;
delete [] ar2;
}
using namespace std is your problem.
Looks like the Microsoft implementation of either the iostream or fstream headers themselves include algorithm. This is causing the name clash with std::count().
So, as #Retiredninja suggested, if I choose to replace while(!in.eof()) with while(in >> a >> b) in:
while(!in.eof()) {
in >> a >> b;
am[a-1][b-1] = 1;
}
Does the rest of the code in the while loop remain the same or does it mean, the input has already been read into a and b when the condition is checked in while(in >> a >> b)?
And become the following:
while(in >> a >> b) {
am[a-1][b-1] = 1;
}
or does it remain:
while(in >> a >> b) {
in >> a >> b;
am[a-1][b-1] = 1;
}
I am coding the game connect four for my computer science class, everything was going great then I dont know what happened but I kept getting Sementation faults whenever I tried to run it. Here is my code.
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cctype>
using namespace std;
struct game{
char **board;
char p1;
char p2;
};
void print_board(game p, int r, int c);
bool play(game p, bool gamewon, int r, int c, int pieces);
bool check(int a, int b, game p, int r, int c, int pieces);
int drop(int b, char player, game p, int c);
int main(int argc, char *argv[]){
game p;
int r, c, pieces;
bool gamewon = false;
/*if(argc == 7) {
for(int i = 1; i < argc; i += 2) {
if(argv[i][0]=='-' && argv[i][1]=='r')
r = atoi(argv[i+1]);
else if(!strcmp(argv[i],"-c"))
c = atoi(argv[i+1]);
else if(!strcmp(argv[i],"-p")){
pieces = atoi(argv[i+1]);
while (pieces < 1){
cout << "You cannot have 0 pieces to connect." << endl;
cout << "Please enter a positive, non-zero integer"
<< " for the number of pieces to connect: ";
cin >> pieces;
}
}
else
cout << "Error." << endl;
}
}*/
r = 6;
c = 7;
pieces = 4;
p.board = new char*[r];
for(int i=0; i < r;i++)
p.board[i] = new char[c];
for(int a =0; a < r; a++){
for(int b = 0; b < c; b++)
p.board[a][b] = ' ';
}
print_board(p, r, c);
gamewon = play(p, gamewon, r, c, pieces);
return 0;
}
bool play(game p, bool gamewon, int r, int c, int pieces){
int col, hold = 0, charsPlaced = 0;
char player = 'y';
while(!gamewon){
if(hold != -1){
if(player =='y'){
cout<<"Player 1, what column do you want to put your piece? ";
player = 'r';
}
else{
cout<<"Player 2, what column do you want to put your piece? ";
player = 'y';
}
}
while(true){
if(charsPlaced == r*c) break;
cin>>col;
col--;
if(col <=r && col>= 0) break;
else cout<< "\nPlease enter a value between 1 and " << c << ": ";
if (cin.fail()){
cin.clear();
char d;
cin>>d;
}
}
if(charsPlaced == r*c) break;
hold = drop(col,player, p, c);
if(hold == -1) cout<<"Column is full!\nPlease enter another number between 1 and " << c << ": ";
else{
gamewon = check(hold, col, p, r, c, pieces);
charsPlaced ++;
print_board(p, r, c);
}
}
if(charsPlaced == r*c){
cout<<"No winner! Game is a draw\n";
return true;
}
if(player == 'y')
cout<<"Player 2 is the winner!\n";
else cout<<"Player 1 is the winner!\n";
return true;
}
void print_board(game p, int r, int c){
cout << endl;
for(int a = 0; a < r; a++){
for(int b = 0; b < c; b++)
cout << "|" << p.board[a][b];
cout << "|";
cout << endl;
for(int i = 0; i < c; i++)
cout << "--";
cout << endl;
}
}
bool check(int a, int b, game p, int r, int c, int pieces){
int vertical = 1, horizontal = 1, diagonalone = 1, diagonaltwo = 1, i , j;
cout << i << " " << b << " " << a << endl;
char player = p.board[a][b];
cout << player << endl;
for(i = a + 1; p.board[i][b] == player && i < r; i++, vertical++);
for(i = a - 1; p.board[i][b] == player && i >= 0; i--, vertical++);
if(vertical >= pieces)
return true;
for(j = b - 1; p.board[a][j] == player && j >= 0; j--, horizontal++);
for(j = b + 1; p.board[a][j] == player && j < c; j++, horizontal++);
if(horizontal >= pieces)
return true;
for(i = a - 1, j = b - 1; p.board[i][j] == player && i >= 0 && j >= 0; diagonalone++, i--, j--);
for(i = a + 1, j = b + 1; p.board[i][j] == player && i <= r && j <= c;diagonalone++, i++, j++);
if(diagonalone >= pieces)
return true;
for(i = a - 1, j = b + 1; p.board[i][j] == player && i >= 0 && j <= c; diagonaltwo++, i--, j++);
for(i = a + 1, j = b - 1; p.board[i][j] == player && i <= r && j >= 0; diagonaltwo++, i++, j--);
if(diagonaltwo >= pieces)
return true;
return false;
}
int drop(int b, char player, game p, int c){
if(b >= 0 && b <= c){
if(p.board[0][b] == ' '){
int i;
for(i = 0; p.board[i][b] == ' '; i++)
if(i == 5){
p.board[i][b] = player;
return i;
}
i--;
p.board[i][b] = player;
return i;
}
else{
return -1;
}
}
else{
return -1;
}
}
You are using
char **board;
in your game struct.
But this 2D array is never allocated and yet, you are working with it.
You are missing something like this:
in C:
board = malloc(10 * sizeof(char *));
for (int i = 0; i < 10; i++)
{
board[i] = malloc(10 * sizeof(char));
}
in C++:
board = new char*[10]
for (int i = 0; i < 10; i++)
{
board[i] = new char[10];
}
For starters, if you are in a Linux environment, valgrind is very helpful in finding where your segmentation fault is. To use it, if your program is called hello, just run it as valgrind hello.
Another method to debug these is to put cout or printf statements throughout your code, and observe what the last output was. You are probably indexing beyond the end of an array. Keep in mind that if you declare int x[5], the valid index values are 0 to 4.
You will probably need to change your for loops to < vs. <= so you aren't reading past the last part of the board (keep in mind that arrays are 0 indexed in c++).