如何从txt文件中读取迷宫并将其放入2D数组中

时间:2016-01-03 20:38:18

标签: c++ arrays algorithm maze

我刚开始一个小项目,它读取这样的txt文件:

4
XSXX
X  X
XX X
XXFX

所以我的问题是如何阅读这个并将迷宫放到C ++的2D char数组中。我尝试使用'getline',但我只是让我的代码更复杂。你知道是否有一种简单的方法可以解决这个问题吗?

char temp;
    string line;
    int counter = 0;
    bool isOpened=false;
    int size=0;

    ifstream input(inputFile);//can read any file any name
    // i will get it from user

    if(input.is_open()){

    if(!isOpened){
        getline(input, line);//iterater over every line
        size= atoi(line.c_str());//atoi: char to integer method.this is to generate the size of the matrix from the first line           
    }
    isOpened = true;
    char arr2[size][size];       

    while (getline(input, line))//while there are lines
    {
        for (int i = 0; i < size; i++)
        {

            arr2[counter][i]=line[i];//decides which character is declared

        }
        counter++;
    }

1 个答案:

答案 0 :(得分:3)

您的错误是由于您尝试声明一个大小为非常量表达式的数组。

在您的情况下size表示数组中元素的数量,必须是constant expression,因为数组是静态内存块,其大小必须在编译时在程序运行之前确定。

要解决这个问题,您可以将数组留空括号,大小将根据您放入其中的元素数量自动推算出来,或者 您可以使用std::stringstd::vector然后阅读.txt文件,您可以编写如下内容:

// open the input file
ifstream input(inputFile);

// check if stream successfully attached
if (!input) cerr << "Can't open input file\n";

string line;
int size = 0;     

// read first line
getline(input, line);

stringstream ss(line);
ss >> size;

vector<string> labyrinth;

// reserve capacity
labyrinth.reserve(size);

// read file line by line 
for (size_t i = 0; i < size; ++i) {

    // read a line
    getline(input, line);

    // store in the vector
    labyrinth.push_back(line);
}

// check if every character is S or F

// traverse all the lines 
for (size_t i = 0; i < labyrinth.size(); ++i) {

    // traverse each character of every line
    for (size_t j = 0; j < labyrinth[i].size(); ++j) {

         // check if F or S
         if (labyrinth[i][j] == 'F' || labyrinth[i][j] == 'S') {

             // labyrinth[i][j]  is F or S
         }

         if (labyrinth[i][j] != 'F' || labyrinth[i][j] != 'S') {

             // at least one char is not F or S
         }
    }
}

正如您所看到的,vector已经是&#34;一种&#34; 2D char数组仅具有许多额外提供的工具,允许对其内容进行大量操作。