In: Computer Science
how can I get my program to read one of 4 text files (chosen/ inputted by user, game1.txt, game2, game3, or game4.txt). and place its information into variables, one of which is an array. I sort of understand this, but I don't know how to make my program know which parts of the textfile go into which variables.
my 4 textfiles are in the format: the list of e4-bc need to be entered into my array.
B 35 e4 e5 Bc4 Nc6 Nf3 Bc5 c3 Nf6 h3 Nxe4 d4 d5 Bb3 exd4 Nbd2 Nxf2 e2+ Qe7 Qxe7+ Nxe7 Kxf2 dxc3+ Kf1 Nf5 bxc3 Ng3+ Ke1 Nxh1 Bxd5 O-O g4 Nf2 Rb1 c6 Bc
my variables that those need to be inputted into are in this abstract data type class:
class Game
{
public:
char outcome; //(whether black or white team won)
int numMoves;
string arrayMoves;}
Given below is the code for the question. Please do rate the answer if it helped. Thank you.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
class Game{
public:
char outcome;
int numMoves;
string moves[200];
bool loadFromFile(string
filename){
ifstream
in(filename.c_str());
if(in.fail()){
cout << "ERROR: could not load file "
<< filename << endl;
return false;
}
in >>
outcome;
in >>
numMoves;
for(int i = 0; i
< numMoves; i++)
in >> moves[i];
in.close();
return
true;
}
void print(){
if(outcome ==
'B')
cout << "Black wins" << endl;
else
cout << "White wins" << endl;
cout <<
"No. of moves: " << numMoves << endl;
for(int i = 0; i
< numMoves; i++){
if(i % 8 == 0) //print 8 moves per line
cout << endl;
cout << setw(8) << moves[i] ;
}
}
};
int main(){
string filename;
cout << "Enter game filename: ";
cin >> filename;
Game game;
if(game.loadFromFile(filename))
{
cout << "Loaded game from
file " << filename << endl;
game.print();
}
return 0;
}