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

3
我刚开始做一个小项目,它可以读取像这样的txt文件:
4
XSXX
X  X
XX X
XXFX

所以我的问题是如何读取这个迷宫并将其放入C ++的2D字符数组中。我尝试使用'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
展示你所写的代码并解释它存在哪些不足。 - Scott Hunter
2
请不要要求“给我代码”,请先展示你做了什么以及为什么它没有起作用。谢谢。 - πάντα ῥεῖ
我刚刚编辑了我的问题。 - Syrenthia
你的代码有什么问题? - Galik
问题在于大小。编译器说它应该是常量,但我应该从文本文件中获取它。 - Syrenthia
显示剩余2条评论
1个回答

3
你的错误是因为你试图声明一个大小为非常量表达式的数组。
在你的情况下,代表数组元素数量的 "size" 必须是 常量表达式,因为数组是静态内存块,其大小必须在程序运行之前在编译时确定。
要解决这个问题,你可以将数组留空括号,大小将根据你放入其中的元素数量自动推断,或者使用 std::string 和 std::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 已经是一个“某种程度上”的 2D char 数组,只不过提供了许多额外的工具来对其内容进行各种操作。


那么我怎样才能获取每个字符以检查它是否为'S'或'F'?或者有没有办法将这个向量放入2D字符数组中? - Syrenthia
它对我起作用了。但是我改变了getline(input,getSize),因为编译器给了我一个错误。所以我使用了stoi来改变int。 - Syrenthia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接