usign C++ Write a function to read a Tic-Tac-Toe board into an array. The file f
ID: 3731828 • Letter: U
Question
usign C++
Write a function to read a Tic-Tac-Toe board into an array. The file format is:
The character 'X' means that the 'X' player has taken that square. The character '.' means that the square is currently unclaimed. There is one space between each symbol.
Note: You will need to store the results in a 2D array. The function should take the filename as a parameter.
Write a function to display a Tic-Tac-Toe board on the screen. Given the above board, the output is:
Write a function to write the board to a file. The file format is the same as with the read function.
Example
The user input is underlined.
Explanation / Answer
#include <iostream>
#include <fstream>
using namespace std;
void Read_and_Print(); //function to read from text file and display output
void Write_to_File(char [3][4]); //function to write into a seperate text file
int main(){
Read_and_Print(); //calling function to read from text file and output
return 0;
}
void Read_and_Print(){
cout<<"Enter source filename: "; //user enters filename
string filename;
char rd[3][4]; //2D character array to store the characters read from file
char temp;
cin>>filename;
ifstream file;
file.open(filename.c_str());
if(!file){ //checking if file exits and is opened successfully
cout<<"Error opening file! Program will exit";
}
else{ //file opened successfully
int i,j;
//reading from file and storing in 2D array
for(i=0;i<3;i++){
for(j=0;j<3;j++){
if(file>>temp)
rd[i][j] = temp;
}
}
//displaying array in required format
for(i=0;i<3;i++){
for(j=0;j<3;j++){
if(rd[i][j]=='.'&&j!=2)
cout<<" | ";
else if(rd[i][j]!='.'&&j!=2)
cout<<rd[i][j]<<" | ";
else if(rd[i][j]!='.'&&j==2)
cout<<rd[i][j];
}
if(i!=2)
cout<<" ---+---+--- ";
}
//calling function to write output to seperate text file
Write_to_File(rd);
file.close(); //closing the file after reading
}
}
void Write_to_File(char wr[3][4]){
ofstream file;
string filename;
cout<<" Enter destination filename: ";
cin>>filename; //to input the destination filename
file.open(filename.c_str());
if(!file){ //checking to see if destination file can be opened to write
cout<<"Error writing to file!";
}
else{ //destination file opened successfully. Writing the output in the desired format
int i,j;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
if(wr[i][j]=='.'&&j!=2)
file<<" | ";
else if(wr[i][j]!='.'&&j!=2)
file<<wr[i][j]<<" | ";
else if(wr[i][j]!='.'&&j==2)
file<<wr[i][j];
}
if(i!=2)
file<<" ---+---+--- ";
}
cout<<"File written ";
}
file.close(); //closing the file after writing
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.