Okay, I'm looking at it. Will edit this post shortly.
[edit] Alright. Don't forget the proper includes.
1 2 3 4
|
#include <ciso646>
#include <fstream>
#include <iostream>
#include <string>
|
The first thing you want to do is create the TYPES of things you will be manipulating. In your case, you have a game board of variable use. (It's size is constant; what changes is how many cells in the game board you actually use.)
1 2 3
|
const int MAX_ROWS = 100;
const int MAX_COLS = 100;
typedef char Gameboard[MAX_ROWS][MAX_COLS];
|
Now you can create the global objects your game uses. (Yes, this is perfectly fine.)
1 2 3
|
Gameboard gameboard;
int rows = 0;
int cols = 0;
|
Next, you want to create FUNCTIONS that do stuff TO or WITH your gameboard.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
void LoadGameboard( const string& filename )
{
// Open the named file
ifstream f( filename );
// Get the number of rows and columns
f >> rows >> cols;
// Skip all whitespace to the first element of the gameboard
f >> ws;
// (It is a good idea to check that your input is safe.)
if ((rows > MAX_ROWS) or (cols > MAX_COLS))
throw "File contains gameboard that is too large.";
// For each row
for (int row = 0; row < rows; row++)
{
// For each column
for (int col = 0; col < cols; col++)
{
// Get the puzzle piece
f >> gameboard[row][col];
}
// Skip to the beginning of the next row (if any)
f >> ws;
}
// (Make sure that the gameboard loaded properly)
if (f.fail())
throw "File contains invalid gameboard.";
}
|
Another useful function, using the same kind of double loop:
1 2 3 4
|
void DisplayGameboard()
{
... // (you fill in the code here)
}
|
Your main function, then, is much simpler:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
int main()
{
// Ask the user for the game board file name
string filename;
cout << "Gameboard filename? ";
getline( cin, filename );
// Load it (if possible)
LoadGameboard( filename );
...
// Use it
bool done = false;
while (!done)
{
DisplayGameboard();
// Get user input
// etc
}
}
|
If you want to see those error messages if something goes wrong, wrap stuff in a
try..catch block. You can put one around the entire main function if you wish:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
int main()
{
try {
// Ask the user for the game board file name
string filename;
cout << "Gameboard filename? ";
getline( cin, filename );
// Load it (if possible)
LoadGameboard( filename );
...
// Use it
bool done = false;
while (!done)
{
DisplayGameboard();
// Get user input
// etc
}
}
catch (const char* error_message)
{
cerr << error_message << "\n";
}
}
|
Hope this helps.