我正在写码在文本的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的?

我已经编码了几个小时,所以我认为这是一个简单的错误,我不是那个醒目跳脱我现在。谢谢!

有帮助吗?

解决方案

尝试像 “C:\ MyMazes \迷宫” 绝对路径。

扔在一个系统(“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;

其他提示

您可以检查从文件提取是否合理:good()的使用ifstream API

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
}

OR

在开始本身:

ifstream loadMaze("maze"); 
if(!loadMaze.good())
{
  //ERROR
}

尝试添加线

if (!loadMaze) throw 1;

loadMaze的声明之后,如果该文件不存在,这将抛出异常。这是一个黑客,你真的应该抛出一个真正的错误。但它的工作原理进行测试。

检查文件开口是否失败与否。您可以通过检查发现这一点,如果这是很好的:

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

如果文件打开失败,然后尝试在绝对路径写入文件(C:/ Documents和设置/.../迷宫),看看是否可以工作。如果是这样,它只是这是错误的文件路径,你就会有与玩。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top