Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello, I am trying to create a 2D array from a text file and I am getting a segm

ID: 654453 • Letter: H

Question

Hello,

I am trying to create a 2D array from a text file and I am getting a segmentation fault. The array is based on a N x M grid like the below:

from the text file:

1 0 0 1 0 0 1

1 0 0 1 0 0 1

0 0 1 0 0 1 0

Another example from the inputted text file

0 0 0 0 0 0 1

1 1 0 0 0 0 1

0 0 0 0 1 0 0

0 1 1 1 1 0 0

0 0 1 0 1 0 1

Here is the code I have written so far:

#include <iostream>

#include <string>

#include <fstream>

#include <cstdlib>

#include <math.h>

#include <algorithm>

using namespace std;

int SIZE = 0;

int R_MAX = 10;

int C_MAX = 10;

int main(){

ifstream myfile;

char file[300];

string coinArr[R_MAX][C_MAX];

int i, j, row, col;

do{

cout << "Please enter file to read: ";

  cin >> file;

  myfile.open(file);

  

  if(myfile.fail()){

  cout << "File could not be opened. Please try again." << endl;

  }

  } while (myfile.fail());

while(!myfile.eof()){

col++;

if(col == ' '){

row++;

}

myfile >> coinArr[row][col];

}

for(i = 0; i < row; i++){

for(j = 0; j < col; j++ ){

  myfile >> coinArr[i][j];

cout << coinArr[i][j];

}

}

cout << endl;

cout << "Done." << endl;

myfile.close();

return 0;

}

Explanation / Answer

#include <iostream>

#include <string>

#include <fstream>

#include <cstdlib>

#include <math.h>

#include <algorithm>

using namespace std;

// Declarations.

int rows;
int columns;
int i;
int j;
char mazesize[][100];
char mazetext;
string s = " ";
string solve;
ifstream maze;
void readMaze (char mazesize[][100], int &rows, int &columns)

{
maze.open ("Maze3.txt");
if (!maze)

{
cout << "Error opening file" << endl;
system ("pause");
maze.close();
}
//Read how many rows and columns are in the maze.
maze >> rows >> columns;
//Print number of rows and columns in the maze.
cout << endl;
cout << "Unsolved Maze:" << endl;
cout << "This maze has " << rows << " rows" << " and " << columns << " columns." << endl;
//Create maze with proper amount of rows and columns.
while (!maze.eof())

{
//maze.get(mazetext);
for ( i = 0; i < rows; i ++)

{
getline (maze, s);
for ( j = 0; j < columns; j ++)

{
mazesize[i][j] = s [j];

}
}

//cout << mazetext;
cout << mazesize[i][j];
}
}
void solveMaze (int &rows, int &columns)

{
}
void printMaze (int rows, int columns)

{
}
int main()

{
char mazesize[100][100];
cout << "Enter 'Solve' to solve the maze" << endl;
cin >> solve;
if (solve == "Solve")

{
readMaze(mazesize, rows, columns);
solveMaze(rows, columns);
printMaze(rows, columns);
}
maze.close();
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote