In C++, while editing the following code. How can you check to see if the file i
ID: 3938237 • Letter: I
Question
In C++, while editing the following code. How can you check to see if the file is open or not. If not ask for the file name again untill they enter a valid txt file name. It needs to loop until a valid name is inputed.
===================================================
void Pokedex::readdata()
{
char filename[20];
int i = 0;
cout << "What is the name of the file?(pokemon.txt): ";
cin.getline(filename, 20);
ifstream inputfile;
inputfile.open(filename);
inputfile.get(creatures[i].name,SIZE,',');
while(!inputfile.eof() && i < SIZE)
{
inputfile.ignore(SIZE, ',');
inputfile.get(creatures[i].type,SIZE,',');
inputfile.ignore(SIZE,',');
inputfile >> creatures[i].hitpoints;
inputfile.ignore(SIZE, ',');
inputfile >> creatures[i].attack;
inputfile.ignore(SIZE, ',');
inputfile >>creatures[i].defense;
inputfile.ignore(SIZE, ',');
inputfile >>creatures[i].ability;
inputfile.ignore(SIZE, ' ');
++i;
++count;
inputfile.get(creatures[i].name,SIZE,',');
}
cout << "You have loaded " << count <<" pokemon.";
inputfile.close();
}
Explanation / Answer
void Pokedex::readdata()
{
char filename[20];
int i = 0;
cout << "What is the name of the file?(pokemon.txt): ";
cin>>filename;
ifstream inputfile;
inputfile.open(filename);
while(inputfile.fail())//checks whether file is opened or availble or not
{
inputfile.clear();
cout<<"file not found,please enter again:";
cin>>filename;
inputfile.open(filename);
}
inputfile.get(creatures[i].name,SIZE,',');
while(!inputfile.eof() && i < SIZE)
{
inputfile.ignore(SIZE, ',');
inputfile.get(creatures[i].type,SIZE,',');
inputfile.ignore(SIZE,',');
inputfile >> creatures[i].hitpoints;
inputfile.ignore(SIZE, ',');
inputfile >> creatures[i].attack;
inputfile.ignore(SIZE, ',');
inputfile >>creatures[i].defense;
inputfile.ignore(SIZE, ',');
inputfile >>creatures[i].ability;
inputfile.ignore(SIZE, ' ');
++i;
++count;
inputfile.get(creatures[i].name,SIZE,',');
}
cout << "You have loaded " << count <<" pokemon.";
inputfile.close();
}