Write a C++ program to read in a Tic-Tac-Toe board, make a move, then save the b
ID: 3828359 • Letter: W
Question
Write a C++ program to read in a Tic-Tac-Toe board, make a move, then save the board back to the file.
Input:
The input will be given on the command line. The first argument is the name of the file containing the game board. The second argument is the letter of who to move as, X or O.
If the letter provided is 'X' (case-INsensitive), play as the letter 'X'. Any other letter will result as playing as 'O'.
Game Board File:
The file holding the game board is made up of 3 lines, 4 chars each. The first 3 chars of a line representing the row of the TTT board. The last char is " ".
The 3 chars for the rows of the TTT board may be 'X', 'O', or space.
Here is an example:
Output:
The output of your project 4 should be:
1. The resulting game board after your move
2. Who won, tie game, else nothing.
Example:
Execution:
Your program, when launched with the above command-line parameters, should:
Obtain the game board file name and player to move as
Read in the game board
Make a move as the specified player
Save the resulting game board to the same file.
State a winner or tie, if applicable
Quit
Explanation / Answer
Here is the below C++ code:
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
void readFile(char ticTacBoard[][9]);
void writeFile(char ticTacBoard[][9]);
void display(char ticTacBoard[][9]);
int main()
{
char ticTacBoard[9][9];
readFile(ticTacBoard);
display(ticTacBoard);
writeFile(ticTacBoard);
return 0;
}
void display(char ticTacBoard[][9])
{
cout << " " << ticTacBoard[0][0] << " | " << ticTacBoard[1][0] << " | " << ticTacBoard[2][0] << " " << endl
<< "---+---+---" << endl
<< " " << ticTacBoard[0][1] << " | " << ticTacBoard[1][1] << " | " << ticTacBoard[2][1] << " " << endl
<< "---+---+---" << endl
<< " " << ticTacBoard[0][2] << " | " << ticTacBoard[1][2] << " | " << ticTacBoard[2][2] << " " << endl;
}
void readFile(char ticTacBoard[][9])
{
char sourceFile[256];
ifstream fin;
cout << "Enter source filename: ";
cin >> sourceFile;
fin.open(sourceFile);
if (fin.fail())
{
cout << "Input file opening failed. ";
exit(1);
}
for (int i = 0; i <= 9; i++)
{
fin >> ticTacBoard[i];
}
fin.close();
}
void writeFile(char ticTacBoard[][9])
{
ofstream fout;
char destinationFile[256];
cout << "Enter destination filename: ";
cin >> destinationFile;
fout.open(destinationFile);
if (fout.fail())
{
cout << "Output file opening failed. ";
exit(1);
}
else
cout << "File written";
for (int i = 0; i <= 9; i++)
{
fout << ticTacBoard[i-1] << " ";
if (i % 3 == 0)
{
fout << endl;
}
}
fout.close();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.