Reputation: 906
I'm writing code to read in a 7x15 block of text in a file that will represent a 'maze'.
#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;
}
this was my original draft but this didnt work as it kept returning ? for each char it read. This is the maze im testing with:
############# # ############ # # ######### #### # ! # ############
EDIT: The cout is printing this:
############# # ############ # # ######### #### # ! # #########
Am I not escaping \n's?
I've been coding for a few hours so I think its a simple mistake I'm not catching that's tripping me up right now. Thanks!
Upvotes: 2
Views: 2788
Reputation: 34621
Try an absolute path like "c:\MyMazes\maze".
Throw in a system("cd") to see where the current directory is. If you're having trouble finding the current directory, check out this SO discussion
Here's the complete code - this should display your entire maze (if possible) and the current directory.
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;
Upvotes: 3
Reputation: 59673
Check whether the file opening failed or not. You can find this out by checking if it's good:
http://www.cplusplus.com/reference/iostream/ios/good/
If the file opening has failed, then try writing in the absolute path to the file (C:/Documents and Settings/.../maze), to see whether that works. If it does, it's just the file path that's wrong, and you'll have to play with that.
Upvotes: 0
Reputation: 67829
try adding the line
if (!loadMaze) throw 1;
after the declaration of loadMaze, this will throw an exception if the file isn't there. This is a hack, really you should throw a real error. But it works to test.
Upvotes: 0
Reputation: 35460
Can you check whether extraction from file is proper: using good()
API of ifstream
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
in the beginning itself:
ifstream loadMaze("maze");
if(!loadMaze.good())
{
//ERROR
}
Upvotes: 0