Hello I am new at c++ and I was wondering, how would I write variables to a file so I can open them later on. I was wondering this because I was going to make a text based game to start out with, in c++. Also I was wondering how hard would making a 2D game would be.

Thanks,
gangsta gama

Member Avatar for iamthwee

To write to a file you can use fstreams.

Making a 2D game is hard, that much I'll say.

If you're serious about making a game, you should really write out (or type out) what is that you want to do in your game.

Make a list with boxes next to each item (or "thing to do" ) then start programming around your list. Find out whats easy to do and what's difficult. Check off anything that is "complete" but don't do it in pen because you may end up going back to that box when something goes wrong.

Try to keep the tasks self-contained, unless tasks must absolutely communicate with each other. A good example is a method. Does this method inquestion really need to access another method, or variables that are responsible for the functionality of another method?

The list of suggestions can go on... then again we really don't know how new you are. You could be developed in another programming language or completely fresh. It's hard to give any concrete advice unless we know what you're doing (by showing us the progress of your code), and know what it is that you want to do.

What I suggest is that you start creating your game and if you have any syntax problems or problems thinking of ideas on how to improve your code such that it functions the way you want then keep coming back here.

Thank you Alex and iamthwee.

Your posts were very helpful, I will keep them in mind, but I am wondering how to write variables to files. If you are confused(I know I am probably not clear enough) I have an example code posted below

#include <iostream>
#include <fstream>
#include <iostream.h>
using namespace std;

int main () {
  int myvar;
  ofstream myfile;
  myfile.open ("somthing.txt");
  cout << myvar;
  myfile.close();
  system("PAUSE");
  return 0;
}

Thank you for your help and time. I know you guys will be seeing me on the boards often. :)

Thank you Alex and iamthwee.

Your posts were very helpful, I will keep them in mind, but I am wondering how to write variables to files. If you are confused(I know I am probably not clear enough) I have an example code posted below

#include <iostream>
#include <fstream>
#include <iostream.h>
using namespace std;

int main () {
  int myvar;
  ofstream myfile;
  myfile.open ("somthing.txt");
  cout << myvar;
  myfile.close();
  system("PAUSE");
  return 0;
}

Thank you for your help and time. I know you guys will be seeing me on the boards often. :)

Close. One, you didn't initialize myvar, so who knows what it will display. Two, why do you have iostream.h? You already have iostream. Three, don't use cout; use myfile, like this:

#include <iostream>
#include <fstream>
#include <iostream.h>  // Why do you have this line?
using namespace std;

int main () {
  int myvar = 8;  // initialize myvar
  ofstream myfile;
  myfile.open ("somthing.txt");
  myfile << myvar;
  myfile.close();
  system("PAUSE");
  return 0;
}

This will write the number 8 to the file "somthing.txt".

Awesome, thanks Vernon.

Also I was wondering if I were to make a long text game, how would go about having the player save their game?

Thank you everyone for your help. I greatly appreciate it.
gangsta gama

Awesome, thanks Vernon.

Also I was wondering if I were to make a long text game, how would go about having the player save their game?

Thank you everyone for your help. I greatly appreciate it.
gangsta gama

There are many possible ways of doing this. It all depends on the game, and even within a game there could be many different ways of saving a game. I assume you want to save this game to a text file? If the game were, say, tic-tac-toe and the board was like this:

x o
o x o
  x

you could save it like this in a text file (just replacing the spaces with a *:

xo*
oxo
*x*

Save the game, then next time you play the game, specify that text file, read the data above from that text file (using an ifstream) into a 3 x 3 character grid or however you are storing the board data, and resume where you left off in the game.

Can't get much more specific than that since it depends on the game and how you are deciding to code the game. Generally you'll have at least two functions:

void SaveGame();
void ResumeGame();

By the way, these aren't necessarily void functions and they could take parameters. The first function would almost definitely involve an ofstream and the second would almost definitely use an ifstream.

I am sorry Vernon, but I do not understand what you are saying. If you could give me an example code to make it a lot clearer that would be helpful.

Thank you.

I am sorry Vernon, but I do not understand what you are saying. If you could give me an example code to make it a lot clearer that would be helpful.

Thank you.

We're not supposed to give full solutions, but since you didn't ask for Tic-Tac-Toe code and it's only intended as a simple example of how saving a text game could work, which you'll have to change for your own purposes, it should be fine. This is a nearly complete Tic-Tac-Toe game with an option to save and resume a game. It doesn't check for bad/illegal input and it doesn't check to see whether the game is over or who won, so it'll be easy to crash, and if you don't quit, eventually the computer will have no place to move so it'll end up in an infinite loop. That said, it's a good example of how you can save and resume a game using ifstream and ofstream.

The key things to look at is the 3 x 3 board array which stores everything, and the functions SaveGame and ResumeGame. Please note that spaces have been changed to asterisks when saving to and reading from files since the << and >> operators can't handle white space. I'm not sure how much C++ experience you've had and whether you're familiar with code like this, but please feel free to ask follow-up questions regarding the code, its limitations, and how to run it. Hope this helps.

// Filename:TicTacToe.cpp

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

char board[3][3];

void DisplayBoard();
void GetPlayerMove();
void GetComputerMove();
bool GameOver();
void SaveGame();
void ResumeGame();

int main()
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
            board[i][j] = ' ';
    }
    
    srand(time(NULL));
    cout << "Hello.  This is a tic-tac-toe game.\n";
    cout << "Do you have a saved game you want to resume (Y/N)?";
    char savedGame;
    cin >> savedGame;
    
    if (savedGame == 'Y')
        ResumeGame();
    
    while (!GameOver ())
    {
        DisplayBoard();
        cout << "Enter 'S' to save game or 'E' to enter a move or 'Q' to quit: ";
        char choice;
        cin >> choice;
        
        if (choice == 'S')
        {
            SaveGame();
        }
        else if (choice == 'E')
        {
             GetPlayerMove();
             if (!GameOver())
                 GetComputerMove();
        }
        else if (choice == 'Q')
        {
             cout << "Thanks for playing." << endl;
             return 0;
        }
    }

    return 0;
}    


void DisplayBoard()
{
     cout << endl;
     for (int i = 0; i < 3; i++)
     {
         for (int j = 0; j < 3; j++)
         {
             cout << board[i][j];
             if ( j < 2)
                 cout << '|';
             else
                 cout << endl;
         }
         
         if (i < 2)
             cout << "-----" << endl;
     }
     
     cout << endl;         
}


void GetPlayerMove ()
{
     int row, col;
     
     cout << "Enter row: ";
     cin  >> row;
     cout << "Enter col: ";
     cin  >> col;
     
     board[row][col] = 'X';
}


void GetComputerMove ()
{
     bool validMove = false;
     while (!validMove)
     {
           int row = rand() % 3;
           int col = rand() % 3;
           if (board[row][col] == ' ')
           {
               validMove = true;
               board[row][col] = 'O';
           }
     }
}     


bool GameOver()
{
     return false;
     
     // change to check for winners and cats game
}


void SaveGame()
{
     cout << "Enter filename to save: ";
     string filename;
     cin >> filename;
     ofstream gameFile;
     gameFile.open(filename.c_str());
     for (int i = 0; i < 3; i++)
     {
         for (int j = 0; j < 3; j++)
         {
             if (board[i][j] == ' ')
                 gameFile << '*';
             else
                 gameFile << board[i][j];
         }
         
         cout << endl;
     }
     gameFile.close();
}


void ResumeGame()
{
     cout << "Enter filename of saved game: ";
     string filename;
     cin >> filename;
     ifstream gameFile;
     gameFile.open(filename.c_str());
     for (int i = 0; i < 3; i++)
     {
         for (int j = 0; j < 3; j++)
         {
             gameFile >> board[i][j];
             if (board[i][j] == '*')
                 board[i][j] = ' ';
         }
    }
    gameFile.close();        
}

Vernon, thank you for posting the game for me. I know this thread was about i/o stream, but I have a few questions about the code. (I am new to c++ programming).

1. When you put:

for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
            board[i][j] = ' ';
    }

For the main function, the display board function, the save game function, and the resume function, what does the i, j, , [j] mean?

Thank you for your help. :)

Vernon, thank you for posting the game for me. I know this thread was about i/o stream, but I have a few questions about the code. (I am new to c++ programming).

1. When you put:

for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
            board[i][j] = ' ';
    }

For the main function, the display board function, the save game function, and the resume function, what does the i, j, , [j] mean?

Thank you for your help. :)

for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 3; j++)
        board[i][j] = ' ';
}

i and j are variables of type integer (see red highlighting). [j] are the array subscripts. i and j should always be 0, 1, or 2 since this is a 2-dimensional 3 x 3 character array, thus the legal subscripts are 0, 1, and 2. When asked for the row and column in the program, you should enter 0, 1, or 2 for the same reason.

Here's a link for a C++ array tutorial. There are many out there. Just google "C++ array tutorial". cplusplus.com is a good resource and this link deals with both single and multidimensional arrays, so I linked it, but there are many others.

http://www.cplusplus.com/doc/tutorial/arrays.html


a b c
d e f
g h i

If the board array was above, board[2][1] would be row 2, column 1, or 'h'. So if i = 2 and j = 1, board[j] would equal 'h'.

Thank you again Vernon. I think I am starting to get it now. Just one more question (so far).
If I made a text game and it starts you at level 1, and the player got to level 2, and wanted to stop, could you tell me how I could have him save his game without losing everything?

Thank you again for the information.

Thank you again Vernon. I think I am starting to get it now. Just one more question (so far).
If I made a text game and it starts you at level 1, and the player got to level 2, and wanted to stop, could you tell me how I could have him save his game without losing everything?

Thank you again for the information.

Anything that can be stored in the variables in your game can be saved in a file. In your game you need to define explicitly what you mean by "everything". There are twenty zillion games out there, so what you store could be anything (i.e. character name, character weapon, number of lives left, what level the player is on, score, etc.). Figure out EXACTLY what needs to be stored in order to resume play. From that, think of a text format that you want to save in. In my example it was a 3 x 3 character grid. That's certainly not the only way to store a Tic-Tac-Toe game. The important thing is to pick a way and use it for BOTH the saving function AND the resume function. They have to match. Until you actually get specific with the game, it's impossible to answer any more thoroughly, I think.

Anything that can be stored in the variables in your game can be saved in a file. In your game you need to define explicitly what you mean by "everything". There are twenty zillion games out there, so what you store could be anything (i.e. character name, character weapon, number of lives left, what level the player is on, score, etc.). Figure out EXACTLY what needs to be stored in order to resume play. From that, think of a text format that you want to save in. In my example it was a 3 x 3 character grid. That's certainly not the only way to store a Tic-Tac-Toe game. The important thing is to pick a way and use it for BOTH the saving function AND the resume function. They have to match. Until you actually get specific with the game, it's impossible to answer any more thoroughly, I think.

For the tic tac toe game you put for save game:

void SaveGame()
{
     cout << "Enter filename to save: ";
     string filename;
     cin >> filename;
     ofstream gameFile;
     gameFile.open(filename.c_str());
     for (int i = 0; i < 3; i++)
     {
         for (int j = 0; j < 3; j++)
         {
             if (board[i][j] == ' ')
                 gameFile << '*';
             else
                 gameFile << board[i][j];
         }
         
         cout << endl;
     }
     gameFile.close();
}

If I were to save a level would I do this (lvl gets converted to plvl(player lvl) during resume):

void SaveGame()
{
     ofstream gameFile;
     gameFile.open(level.c_str());
         gameFile << plvl=lvl;
         cout << endl;
     }
     gameFile.close();
}

Thank you again. :icon_lol:

For the tic tac toe game you put for save game:

void SaveGame()
{
     cout << "Enter filename to save: ";
     string filename;
     cin >> filename;
     ofstream gameFile;
     gameFile.open(filename.c_str());
     for (int i = 0; i < 3; i++)
     {
         for (int j = 0; j < 3; j++)
         {
             if (board[i][j] == ' ')
                 gameFile << '*';
             else
                 gameFile << board[i][j];
         }
         
         cout << endl;
     }
     gameFile.close();
}

If I were to save a level would I do this (lvl gets converted to plvl(player lvl) during resume):

void SaveGame()
{
     ofstream gameFile;
     gameFile.open(level.c_str());
         gameFile << plvl=lvl;
         cout << endl;
     }
     gameFile.close();
}

Thank you again. :icon_lol:

void SaveGame()
{
     ofstream gameFile;
     gameFile.open(level.c_str());  // is "level" the filename?
         gameFile << plvl=lvl;     // gameFile << lvl;
         cout << endl;
     }   // delete.  Extra bracket
     gameFile.close();
}

See comments in red. If the level is stored in lvl and that's what you want to write it to the file, just do this:

gameFile << lvl;

If you want to assign the value of lvl to plvl when you RESUME play, after you read the data in from the file, do it in the ResumeGame() function not the SaveGame() function. Yes, ResumeGame() and SaveGame() will need to match, but they won't necessarily be identical. You could be doing some things in one of them that you aren't in the other. But this:

gameFile << plvl=lvl;

is a syntax error. You could do the code below if you wanted, but again, I would put the plvl=lvl line in the ResumeGame() function instead.

plvl = lvl;
gameFile << plvl;

how would resume game look?

Thanks :)

For the tic tac toe game you put for save game:

void SaveGame()
{
     cout << "Enter filename to save: ";
     string filename;
     cin >> filename;
     ofstream gameFile;
     gameFile.open(filename.c_str());
     for (int i = 0; i < 3; i++)
     {
         for (int j = 0; j < 3; j++)
         {
             if (board[i][j] == ' ')
                 gameFile << '*';
             else
                 gameFile << board[i][j];
         }
         
         cout << endl;
     }
     gameFile.close();
}

If I were to save a level would I do this (lvl gets converted to plvl(player lvl) during resume):

void SaveGame()
{
     ofstream gameFile;
     gameFile.open(level.c_str());
         gameFile << plvl=lvl;
         cout << endl;
     }
     gameFile.close();
}

Thank you again. :icon_lol:

Whoops! My bad! Change line 18 below:

void SaveGame()
{
     cout << "Enter filename to save: ";
     string filename;
     cin >> filename;
     ofstream gameFile;
     gameFile.open(filename.c_str());
     for (int i = 0; i < 3; i++)
     {
         for (int j = 0; j < 3; j++)
         {
             if (board[i][j] == ' ')
                 gameFile << '*';
             else
                 gameFile << board[i][j];
         }
         
         cout << endl;
     }
     gameFile.close();
}

from

cout << endl;

to

gameFile << endl;

In this particular game it didn't make a difference since C++ ignores all newlines using the >> operator when it reads the file in later, but my intention was to have that endl go to the file, not the screen, so cout is incorrect here.

how would resume game look?

Thanks :)

I imagine ResumeGame() would be something like this, assuming level is the filename.

void ResumeGame()
{
     ifstream gameFile;
     gameFile.open(level.c_str()); 
     gameFile >> lvl; 
     plvl = lvl;
     gameFile.close();
}

Thank you,
I get 10 errors on this code (just practicing). Can you please tell me whats wrong?

#include<iostream.h>
#include<fstream>
#include<string>

    int plvl = 1;
    int lvl;
    char a[2];
    char b;
    string filename;
    void resumeGame();
    void saveGame();

void resumeGame()
{
     ifstream gameFile;
     gameFile.open(level.c_str()); 
     gameFile >> lvl; 
     plvl = lvl;
     gameFile.close();        
}

void saveGame()
{
     filename = "level";
     ofstream gameFile;
     gameFile.open(filename.c_str());
     gameFile << lvl;     // gameFile << lvl;
     lvl = plvl;
     gameFile.close();
}

int main()
{    
    cout << "Do you want to resume?";
    cin >> b;
    if (b == 'y' || b == 'Y')
    {
          resumeGame();
    }
    cout << "Your level is " << lvl << endl;
    cout << "Say something" << endl;
    cin >> a;
    cout << "Your level is ";
    lvl = 2;
    cout << lvl << endl;
    saveGame();
    
    system("PAUSE");
    return 0;
}

Errors are:
9: error: `string' does not name a type
15: error: `ifstream' undeclared (first use this function)
15: error: (Each undeclared identifier is reported only once for each function it appears in.)
15: error: expected `;' before "gameFile"
16: error: `gameFile' undeclared (first use this function)
16: error: `level' undeclared (first use this function)
24: error: `filename' undeclared (first use this function)
25: error: `ofstream' undeclared (first use this function)
25: error: expected `;' before "gameFile"
26: error: `gameFile' undeclared (first use this function)

I greatly appreciate your help for everything :)

#include <iostream>
#include <fstream>
#include <string>

using namespace std; // you forgot the std namespace declaration

    int plvl = 1;
    int lvl;
    char a[2];
    char b;
    string filename;
    string level; // wasn't declared
    void resumeGame();
    void saveGame();

void resumeGame()
{
     level = "level";
     ifstream gameFile;
     gameFile.open(level.c_str()); 
     gameFile >> lvl; 
     plvl = lvl;
     gameFile.close();        
}

void saveGame()
{
     filename = "level";
     ofstream gameFile;
     gameFile.open(filename.c_str());
     gameFile << lvl;     // gameFile << lvl;
     lvl = plvl;
     gameFile.close();
}

int main()
{    
    cout << "Do you want to resume?";
    cin >> b;
    if (b == 'y' || b == 'Y')
    {
          resumeGame();
    }
    cout << "Your level is " << lvl << endl;
    cout << "Say something" << endl;
    cin >> a;
    cout << "Your level is ";
    lvl = 2;
    cout << lvl << endl;
    saveGame();
    
    system("PAUSE");
    return 0;
}

Perfect, thank you Alex. It works! :)

Perfect, thank you Alex. It works! :)

There is a better way to represent it, however I'm not too familiar with streams in C++ yet.

You can use this program to help you familiarize yourself on how i/o works in C++.

You'll learn once you practice more with I/O which is an important concept when sending/receiving information period.

Thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.