2

我正在编写代码以读取代表“迷宫”的文件中的 7x15 文本块。

#include <iostream>
#include <fstream>
#include <string>
#include "board.h"  

int main()
{
    char charBoard[7][15];  //the array we will use to scan the maze and modify it
    ifstream loadMaze("maze");  //the fstream we will use to take in a maze
    char temp; //our temperary holder of each char we read in

    for(int i = 0;i < 7; i++)
    {

        for(int j = 0; j < 15; j++)
    {
        temp= loadMaze.get();
        charBoard[i][j] = temp;
        cout << charBoard[i][j];  //testing
    }
    cout << endl;
}

return 0;
}

这是我的原始草稿,但由于它不断返回,所以这不起作用?对于它读取的每个字符。这是我正在测试的迷宫:

  #############
              #
#############
              #
 ######### ####
 #!#   
############   

编辑: cout 正在打印:

  #############


#
############
 #

  #
 #########
####
 #!      
 #   
#########

我不是在逃避 \n 的吗?

我已经编码了几个小时,所以我认为这是一个我没有发现的简单错误,这让我现在绊倒了。谢谢!

4

4 回答 4

3

尝试像“c:\MyMazes\maze”这样的绝对路径。

输入一个 system("cd") 来查看当前目录在哪里。如果您在查找当前目录时遇到问题,请查看此SO 讨论

这是完整的代码 - 这应该显示你的整个迷宫(如果可能的话)和当前目录。

 char charBoard[7][15];      //the array we will use to scan the maze and modify it
 system("cd");
     ifstream loadMaze("c:\\MyMazes\\maze");  //the fstream we will use to take in a maze

 if(!loadMaze.fail())
 {
    for(int i = 0;i < 7; i++)
    {
        // Display a new line
        cout<<endl;
        for(int j = 0; j < 15; j++)
        {
             //Read the maze character
             loadMaze.get(charBoard[i][j]);
             cout << charBoard[i][j];  //testing
        }
        // Read the newline
        loadMaze.get();
    }
    return 0;
 }
 return 1;
于 2009-10-09T04:30:45.570 回答
0

您能否检查从文件中提取是否正确:使用good()APIifstream

for(int j = 0; j < 15; j++)
{
    if(!loadMaze.good())
    {
        cout << "path incorrect";

    }

    temp= loadMaze.get();


    cout << "temp = " << temp << endl; //testing
    charBoard[i][j] = temp;
    cout << charBoard[i][j];  //testing
}

或者

一开始本身:

ifstream loadMaze("maze"); 
if(!loadMaze.good())
{
  //ERROR
}
于 2009-10-09T04:31:55.480 回答
0

尝试添加该行

if (!loadMaze) throw 1;

在声明 loadMaze 之后,如果文件不存在,这将引发异常。这是一个 hack,你真的应该抛出一个真正的错误。但它可以测试。

于 2009-10-09T04:32:12.430 回答
0

检查文件打开是否失败。您可以通过检查它是否良好来发现这一点:

http://www.cplusplus.com/reference/iostream/ios/good/

如果文件打开失败,则尝试写入文件的绝对路径(C:/Documents and Settings/.../maze),看看是否有效。如果是这样,那只是文件路径错误,您将不得不使用它。

于 2009-10-09T04:32:22.530 回答