Attempting to read a file and input it into an array

时间:2016-04-21 22:34:21

标签: c++ arrays

I am currently attempting to read a file into a two dimensional array one digit at a time. The file I am retrieving data is maze.txt (shown below code). The program in its current state compiles, but when the program is ran, nothing is printed and it runs forever. I am assuming that the error is associated with the first for loop.

This is the output of Chris's solution

//Input: A txt file containing a 10 x 10 maze of 0s and 1s
//Output: A route from the top left to the bottom right passing through only 0s
#include <fstream>
#include <iostream>
using namespace std;
const int LENGTH = 10;
const int WIDTH = 10;


int main()
{ char mazeArray[LENGTH][WIDTH];
  int counter = 0;
  fstream mazeFile;
  mazeFile.open("maze.txt");
  if(mazeFile.fail())
  {
    cout << "File not found." << endl;
    return 0;
  }
do
  {
    cin >> mazeArray[counter];
    counter++;
  } while(mazeFile.good() && counter < LENGTH * WIDTH );

for(int j = 0; j > 100; j++)
  {
    cout << mazeArray[j] << endl;
  }


  return 0;
}

Maze.txt

0 1 0 0 1 0 0 1 0 0
0 0 1 1 1 0 0 0 0 1
1 0 1 0 1 0 1 0 1 0 
0 0 0 0 1 0 1 0 1 0 
0 0 0 1 0 0 1 0 1 0 
1 1 0 0 0 0 1 0 1 0 
1 1 1 1 1 0 0 0 1 0 
0 0 0 0 0 1 0 0 0 0 
1 1 1 1 1 1 0 1 0 0
0 0 0 0 0 0 0 1 1 0 

1 个答案:

答案 0 :(得分:2)

Your issue is that you are incorrectly evaluating the variable j in your for loop.

You have:

for(int j = 0; j > 100; j++)
  {
    cout << mazeArray[j] << endl;
  }

However, this loop will never execute as j starts out at 0, and then is checked to see if 0>100. The correct loop to iterate through this would be:

for(int j = 0; j < LENGTH; j++)
for(int i = 0; i < WIDTH; i++)
  {
    cout << mazeArray[j][i] << endl;
  }

Your secondary issue is that you are trying to read the file stream mazeFile by using cin. You should replace the line:

cin >> mazeArray[counter];

with:

mazeFile >> mazeArray[counter];

This is not causing it to run 'infinitely' but rather causing it to await an input from standard input. (Most likely text entered via the terminal.)

A fixed code sample is:

#include <fstream>
#include <iostream>
using namespace std;
const int LENGTH = 10;
const int WIDTH = 10;


int main()
{ int mazeArray[LENGTH][WIDTH];
  int counter = 0;
  fstream mazeFile;
  mazeFile.open("maze.txt");
  if(mazeFile.fail())
  {
    cout << "File not found." << endl;
    return 0;
  }
do
  {
      // Now accessing the array as a 2d array to conform to best practices.
    mazeFile >> mazeArray[counter/LENGTH][counter%WIDTH];
    counter++;
  } while(mazeFile.good() && counter < LENGTH * WIDTH );

for(int j = 0; j < LENGTH; j++)
for(int i = 0; i < WIDTH; i++)
  {
    cout << mazeArray[j][i] << endl;
  }


  return 0;
}