Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ I am working on a console game that when it starts up it opens a text file.

ID: 3851129 • Letter: C

Question

C++ I am working on a console game that when it starts up it opens a text file. After the players reads the rules, it is suppose to close the text file when the player presses any key to play. Then the player can input how many players on the new screen. I can't get the text file to close, so the players can enter the number of players on the new screen. What am I doing wrong?

#include "stdafx.h"
#include <iostream>
#include <fstream>


using namespace std;

int main()
{
   ifstream inputFile;

   ifstream f("Text.txt");//associates the text file

   cout << "Liar's Dice Copy" << endl;

   if (f.is_open())//if true then allow open stream object.
       cout << f.rdbuf();//Get/set stream buffer
  
   cout << "Press any key to play" << endl;

   inputFile.close(); // should close text file

   getchar(); // gets key input

int numplayers;// declares numplayers

   cout << "Enter Number of Players:" << endl; //print on screen
   cin >> numplayers;// outputs number of players
}

Explanation / Answer


#include <iostream>
#include <fstream>

using namespace std;
int main()
{
ifstream inputFile; // no need of this line as it is not used
ifstream f("C:\Text.txt");//associates the text file with the variable 'f'
cout << "Liar's Dice Copy" << endl;
if (f.is_open())//if true then allow open stream object.
cout << f.rdbuf();//Get/set stream buffer
  
cout << "Press any key to play" << endl;
  
getchar(); // gets key input
f.close(); // should close text file

int numplayers;// declares numplayers
cout << "Enter Number of Players:" << endl; //print on screen
cin >> numplayers;// outputs number of players
}