School capstone project

Hello, I am writing a code for my school project about a camping simulation, but I need to write a save and load the file but I'm a little confused on how to. This is what I have so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include<iostream>
#include<string>
#include<stdlib.h>
#include<cstdlib>
#include<fstream>

using namespace std;
int main() {
	string saveload;
	cout << "Welcome to the program!\n" << endl;
	cout << "---------------------------" << endl;
	cout << "| save - Save to a file   |" << endl;
	cout << "| load - Load from a file |" << endl;
	cout << "---------------------------\n" << endl;

	getline(cin, saveload);

	if (saveload == "load") {

		ifstream loadFile;

		loadFile.open("Save.txt", ifstream::in);

		cout << "The file contained: ";

		while (loadFile.good()) {

			cout << (char)loadFile.get();

		}

		cout << "" << endl;

		loadFile.close();

	}

	if (saveload == "save") {

		string textToSave;
		cout << "" << endl;
		getline(cin, textToSave);
		ofstream saveFile("Save.txt");
		saveFile << textToSave;
		saveFile.close();

	}

	return 1;
}
      while (1) {
		string name;
		cout << "Hello welcome to the camping game simulator! I am so glad you are here, if you want to start this game type in S, if you want to exit this game type in E" << endl; 
		string exit;
		cin >> exit;
		if (exit == "E" || exit == "e")
			return 0;
		string start;
		if (start == "S" || start == "s")
			cin >> start;
		cout << "Okay let's begin our journey of camping! ";
		cout << "The place where you are camping is somewhere in the woods. You pack everything you need to enjoy your day outside in the fresh air and with nature. Once you start to get into your car, clouds start to form around each other and it starts to get darker, but you continue on to your camping site." << endl;
		cout << "\n(#1) You finally arrive at your camping grounds and it starts to rain down, then you hear thunder and lightning, what do you do?" << endl;
		cout << "(1) Stay in car until rain ends" << "\n(2) Start pitching your tent" << "\n(3) Unpack all your equipment" << "\n(4) Make a fire" << endl;

		char option;
		cin >> option;
		if (option == '1')
		{
			cout << "You lock yourself in the car until the rain ends. You are happy." << endl;
		}
		if (option == '2')
		{
			cout << "The wind blows and the rain keeps pouring down hard, you can't see very well, you're holding the medal rod that goes to your tent when lightning strikes it and you are electrocuted. You are unhappy.\n" << endl;
			continue;
		}
		if (option == '3')
		{
			cout << "Your equipment gets soaked, you are tired from unpacking and it starts to get colder, you are miserable and give up and go home, leaving your stuff out. You and the wildlife officers are unhappy.\n" << endl;
			continue;
		}
		if (option == '4')
		{
			cout << "Making a fire is unsuccessful, you are soaked with water and the cold wind is blowing, you go back to your car and try to warm up but the car battery dies and you are stuck in the car with no heat. You are unhappy.\n" << endl;
			continue;
		} 
Last edited on
Please edit your post for readability.
https://www.cplusplus.com/articles/jEywvCM9/
Like that?
So what are you saving and loading? The state of the game? Start by creating a struct or class to store the state. Then write functions to read and write that struct.

You will also have to think about how to start the game from a saved state. You can't start with the "Okay let's begin our journey of camping" prompt. You'll need to print the appropriate prompt for whatever state you saved.

It looks like this is a text adventure game. You may find it easier to write this as a game engine that reads data from a config file and then acts on the config. That's how the original adventure game worked. For special case actions, you just write a bunch of code that basically says "if these specific conditions apply, then call this function. If these other conditions apply, then call this other function." The special conditions might be things like finding your way out of game.
Could you possibly find a video on YouTube or something, this online learning is kind of stressful so reading about it is difficult while showing it is easier, if not then I appreciate the help!
This is also due in three days, so I don't know if I should rewrite the whole code, as I don't think I would have enough time to.
#include<stdlib.h>
#include<cstdlib>
these are the same except you should use the 2nd one, the first is old c++ or C.

what he is telling you is to step away from the code.
you need to design a little, draw a picture or some simple words, figure out WHAT you want to save. Making a file is easy, but it needs to be a part of a bigger picture, and work with the code, rather than be stuffed in as an afterthought.

you don't have to start totally over.
something like this
read the file if the user wants to provide one.
from the file, realize where you are at, and start processing from there.

so instead of 'welcome, lets get started' its
welcome, lets continue, and you print the last thing they saw from their save and offer the appropriate next option to go forward, whatever.

most of what you have can be shuffled around this.
no, there isnt a how to write this exact program tutorial out there.

but see how you have cin option and then do stuff off option?
instead you have file read of the state, and do thing based off saved state and proceed as if they typed it in to get to that point.
another crude way to do it is simply to record all the user's input and replay it silently and when you run out of input, start interacting again, or play only the last couple of records at them and pick up from there. Some simple games do this, its a valid approach.
Last edited on
Would something like this be more reasonable?
1
2
3
4
5
6
7
8
9
10
11
12
	ofstream outputFile;
	ifstream inputFile;
	outputFile.open("myFile.txt");
	if (outputFile.fail()) {
		perror("myFile.txt");
		return 1;
	}
	inputFile.open("myFile.txt");
	if (inputFile.fail()) {
		perror("myFile.txt");
		return 1;
	}
Last edited on
Hello IanTG,

If you put every waking hour into the program you might just make it.

In addition to what dhayden has said I will cover some other points:

Your include statements:
1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
#include<string>
#include <cctype>   // <--- For "std::tolower() and std::toupper()" + others.
#include<stdlib.h>  // <--- C header file.
#include<cstdlib>   // <--- C++ header file. This is the 1 to use.

#include<fstream>

using namespace std;  // <--- Best not to use.

int UnknownFunc();

Lines 4 and 5 are the same with the exception that "cstdlib" is designed to work with C++ programs. You only need "cstdlib" not both.

The int UnknownFunc();" function is to use the while loop that follows "main". As is it just causes an error. I used this to avoid the error and because I do not know if it should be on "main" or a function.

Then in "main":
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
    string saveload;

    cout <<
        "   Welcome to the program!\n"
        " ---------------------------\n"
        " | save - Save to a file   |\n"
        " | load - Load from a file |\n"
        " ---------------------------\n\n";

    UnknownFunc();  // <--- Used for testing.

    getline(cin, saveload);

    if (saveload == "load")

You do not need a "cout" and "endl" for every line. And prefer to use the new line, (\n), over the function "endl".

Each line of a quoted string may look separate, but it is considered just 1 big string, so just ` "cout" to start and 1 (;) to end. This looks more like what you will see on the screen and it is easier to change, i.e., add to or delete from. Such as the last line should be something like " Enter choice: ".

The function is just for testing the while loop that followed "main".

Line 3 defines a "std::string", which will work.

Line 16 tests for "load", but what about "L", :LOad", "LOAD" and other combinations. This if statement could get very large.

It would work better to define "saveload" as a "char" and deal with just 1 character instead of a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
    char saveload{};  // <--- ALWAYS initialize all your variables.

    cout <<
        "   Welcome to the program!\n"
        " ---------------------------\n"
        " | save - Save to a file   |\n"
        " | load - Load from a file |\n"
        " ---------------------------\n"
        "   Enter choice: ";                    // <--- Added.


    UnknownFunc();  // <--- Used for testing.

    cin >> saveload;

    saveload = static_cast<char>(std::toupper(static_cast<unsigned char>(saveload)));  // <--- Added.

    if (saveload == 'L')

This way you only have 1 character to check. The opening message would have to be changed.

For the while loop I did this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
int UnknownFunc()
{
    while (1)
    {
        string name;

        cout <<
            "Hello welcome to the camping game simulator! I am so glad you are here,\n"
            "if you want to start this game type in S,\n"
            "if you want to exit  this game type in E\n";

        string exit;

        //cin >> exit;

        //if (exit == "E" || exit == "e")
        //    return 0;

        //string start;

        //if (start == "S" || start == "s")
        //    cin >> start;

        cout <<
            "\n"
            "Okay let's begin our journey of camping!\n\n"  // <--- The space at the end is unnecessary.
            "The place where you are camping is somewhere in the woods. You pack everything\n"
            "you need to enjoy your day outside in the fresh air and with nature. Once you\n"
            "start to get into your car, clouds start to form around each other and it starts\n"
            "to get darker,but you continue on to your camping site.\n\n";

        cout <<
            "\n(#1) You finally arrive at your camping grounds and it starts to rain down,\n"
            "then you hear thunder and lightning, what do you do?\n\n"
            
            "(1) Stay in car until rain ends\n"
            "(2) Start pitching your tent\n"
            "(3) Unpack all your equipment\n"
            "(4) Make a fire\n"
            "  Eneter choice: ";  // Added. 

On line 5 you define the variable: string name;, but never use it. I am thinking this should be defined in "main" and passed to any function that would need it.

On line 12 you define "exit" as a string, but it should be a "char" based on the menu choices. Also it should have a better name like "choice" or something else.

Line 19 defines "start", but you do not need this.

Line 16 compares "exit" to either case of "e", line 21 should be comparing "exit" to either case of "S".

You are asking for the same thing twice and putting the answer into 2 different variables. Not a good idea. You just need 1 variable to use with the 2 if statements.

I have changed the first "cout" statements. Your original code would look something like this on my screen:

Okay let's begin our journey of camping! The place where you are camping is somewhere in the 
woods. You pack everything you need to enjoy your day outside in the fresh air and with natur
e. Once you start to get into your car, clouds start to form around each other and it starts 
to get darker, but you continue on to your camping site.

(#1) You finally arrive at your camping grounds and it starts to rain down, then you hear thu
nder and lightning, what do you do?
(1) Stay in car until rain ends
(2) Start pitching your tent
(3) Unpack all your equipment
(4) Make a fire


This may look fine on a wider screen, but do not count on that happening.

Notice on the 2nd line how the "e" is wrapped to the next line. Then 4 lines later notice how the word "thunder" is broke up. Not easy to read. You need to think about what this program will be run on and the size of the screen.

A better choice is what I have done. The output looks like:

Okay let's begin our journey of camping!

The place where you are camping is somewhere in the woods. You pack everything
you need to enjoy your day outside in the fresh air and with nature. Once you
start to get into your car, clouds start to form around each other and it starts
to get darker,but you continue on to your camping site.


(#1) You finally arrive at your camping grounds and it starts to rain down,
then you hear thunder and lightning, what do you do?

(1) Stay in car until rain ends
(2) Start pitching your tent
(3) Unpack all your equipment
(4) Make a fire
  Eneter choice:


This makes the lines shorter and quicker to read. Plus it considers being displayed on a smaller screen width.

Your program will work with what you have. You just need to clean some parts up and deal with reading and saving a file.

Andy
Hello IanTG,

Consider this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
ofstream outputFile("myFile.txt");
ifstream inputFile("myFile.txt");

if (!outputFile)  // <--- This is all you need.
{
    //std::cerr << "\n     File " << std::quoted(outFileName) << " did not open\n";  // <--- Requires header file "<iomanip>".
   std::cerr << "\n     File \"" << "myFile.txt" << "\" did not open.\n";

    return 1;
}

if (!inputFile)
{
    //std::cerr << "\n     File " << std::quoted(outFileName) << " did not open\n";  // <--- Requires header file "<iomanip>".
    std::cerr << "\n     File \"" << "myFile.txt" << "\" did not open.\n";

    return 2;
}

You may have a problem opening the same file for input and output at the same time.

If this is done in separate places at different times it would work.

Andy
ofstream will erase any existing contents of the file!
Topic archived. No new replies allowed.