I am trying to read and write a text file into an array and then store it back into the text file. The main problem i am having is the storing the file character by character into the 3D array.
#include <iostream>
#include <fstream>
using std::ofstream;
usingnamespace std;
int main()
{
char cabin[2][3][12];
char ch, res;
int num, lvl=0, row=0, col=0;
ifstream indata;
indata.open("littleswandb.txt");
if(!indata)
{
cout << "File could not be opened" << endl;
system("pause");
return 0;
}
indata >> ch;
while (!indata.eof())
{ // keep reading until end-of-file
num=0;
while(num<4)
{
cout << ch;
indata >> ch;
num =num +1;
} // sets EOF flag if no value found
cout << endl;
}
indata.close();
system("pause");
cout << "Would you like to make a reservation? Y/N" << endl;
cin >> res;
while ((res == 'Y') || (res == 'y'))
{
cout << "Which Level Would you like to reserve? 1-3" << endl;
cin >> lvl;
cout << "Which Row Would you like to reserve? 1-13" << endl;
cin >> row;
cout << "Which Colunm Would you like to reserve? 1-4" << endl;
cin >> col;
lvl = lvl - 1; //Minus 1 for array
row = row - 1; //Minus 1 for array
col = col - 1; //Minus 1 for array
if (cabin[lvl][row][col] != 'X')
{
cabin[lvl][row][col] = 'X';
lvl = lvl + 1; //Plus 1 after array use
row = row + 1; //Plus 1 after array use
col = col + 1; //Plus 1 after array use
cout << "You have booked the Cabin on Level: " << lvl
<< " Row: " << row
<< " Colunm: " << col << endl;
//output the array onto the screen
for(int a=0; a<3; a++)//Levels
{
for(int b=0; b<13; b++)//Rows
{
for(int c=0; c<4; c++)//Colunms
{
cout << cabin[a][b][c];
}
cout << endl;
}
cout << endl;
}
ofstream outdata("littleswandb.txt");
for(int d=0; d<3; d++) // Levels
{
for(int e=0; e<12; e++) //Rows
{
for(int f=0; f<4; f++) // Colunms
outdata<<cabin[d][e][f]; // store array into file
outdata<< endl;
}
outdata<< endl;
}
outdata.close();
system("pause");
}
else
cout << "That cabin is already booked" << endl;
cout << "Would you like to try another cabin? Y/N" << endl;
cin >> res;
}
cout << "Thank you. Good bye." << endl;
system("pause");
return 0;
}
the text file is representing a cruise ship database where 'B' is a balcony cabin, 'W' is a window cabin, and 'I' is an inside cabin. there are 3 levels in the cruise ship, with 4 columns and 13 rows. that is where the 3d array comes in "cabin[2][3][12]".
the following is what is inside a text file named "littleswandb.txt"