繁体   English   中英

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

[英]How to read a labyrinth from a txt file and put it into 2D array

我刚刚开始了一个小项目,它读取这样的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++;
    }

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

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

要解决它,您可以将数组保留为空括号,大小将由您放入其中的元素数自动推断,或者您可以使用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
         }
    }
}

正如您所看到的,此向量已经是“一种”2D char数组,只有许多额外提供的工具允许对其内容进行大量操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM