:sad: how do i save a variable to a file on the hard drive of the computer running it

:?: any one... please?

What kind of information?

like all variables int,strings,float,bool,etc.

I read the about tutorial but is there a way to open a file without the using namespace std; declaration?

example:

#include<iostream>
#include<fstream>


int main()
{
std::fstream myFile("animals.txt",ios::app);

if (! myFile) // Always test file open
    {
        std::cout << "Error opening output file\n";
        return -1;
    }
    
myFile << "Hello, World!\n";
myFile.close();
return 0;

generates a whole slew of errors.

I'm sure you could.
However:
using namespace std gives you access to the C++ standard library.
According to this book(C++: The complete reference) in my lap, the namespace is a declaritive region (whatever that means) that localizes the names of identifiers to prevent collisions (read, confusion).

It allows you to use the appropriate header files is the jist of it. Without the namespace std, you have to switch back to the following:

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

to get the correct results...
Maybe. It might not be that simple. Anyone else know with more certainty?

For most applications, you probably won't need to deviate from the std namespace anyway.

>generates a whole slew of errors.

What's your compiler?
What are the errors? (As in, please post them.)

compiler g++

errors:
file.C: In function `int main()':
file.C:7: `ios' undeclared (first use this function)
file.C:7: (Each undeclared identifier is reported only once for each function
it appears in.)
file.C:7: parse error before `::' token
file.C:9: warning: the address of `std::fstream myFile(...)', will always be
`true'
file.C:15: invalid operands of types `std::fstream ()(...)' and `const char[15]
' to binary `operator<<'
file.C:16: request for member `close' in `myFile(...)', which is of
non-aggregate type `std::fstream ()(...)'

on VC++ 6, Running that code gives me two errors...
'ios' is not a class or namespace name
'app' is an undeclared identifier.

Try this:

std::fstream myFile("animals.txt",std::ios::app);

ios is part of the std namespace, so you were trying to reference something that didn't exist to your compiler.

aha! Thank you very much.

ok I'm trying to save all of these variables:

#include <fstream>
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <conio.h>

using namespace std;


int trainingHut(void);
int forest(void);
void menuFunc(void);
int weaponShop(void);
int forbidenPalece(void);
int field(void);
int rest(void);
int beach(void);
int armorShop(void);
int attackPhase(void);
int deffensePhase(void);
int itemfind(void);
int attackAsk(void);

//inventory
string currentWeapon;
string currentAcessory;
string currentArmor;
string currentShield;
string currentFootwear;


string usedWeapons[200];
int index = 0;

//stats
int hp = 50;
int xp = 0;
int atk = 17;
int lvl = 1;
int def = 14;
int armdef = 0;
int wepatk = 0;
int mana = 15;
int acc = 11;
int eva = 9;
int spllvl = 1;
int totAtk = atk + wepatk;
int totDef = def + armdef;


//monster stuff

string monster;
int monsterHp;
int monsterAtk;
int monsterDef;
int monsterAcc;
int monsterEva;


int damage;
int monsterDamage;
int temporaryAtk = totAtk;
int temporaryDef = totDef;


//all weapons
string maces = "maces";
string clubs = "clubs";
string swords ="swords";
string scimitars = "scimitars";
string axes = "axe";
string daggers = "daggers";

//all defenses
string shield;
string armor;
string helmet;


//all other
string rings;
string footwear;
string gloves;
string necklaces;
string cape;


//all words
string yes;
string Hi;
int menu;
int gold = 500;


//maces
string spikedmaces = "spicked";
string bronzemaces = "bronze";
string ironmaces = "iron";
string silvermaces = "silver";
string icemaces = "ice";
string firemaces = "fire";
string goldmaces = "gold";
string dimondmaces = "dimond";

//armor
string spikedarmor = "spicked";
string bronzearmor = "bronze";
string ironarmor = "iron";
string silverarmor = "silver";
string icearmor = "ice";
string firearmor = "fire";
string goldarmor = "gold";
string dimondarmor = "dimond";


:to a file during the program and then when i start up my program again i want it to cheak and see if the variables are saved to a file like "saveOne" and if so i want the variables that were saved there replace the new ones if not, continue regularly


i saw the tutorial but it just told me how to make it write something not write a variable and then load it again

Ohoho! I see.
There's an easy way to do this, but first, some more information.
For this game, do you have an inventory that allows you to hold multiple copies of armor, for example? Or can you only have one at a time?

Let me just assume that you've got an inventory that only lets you have one particular set of equipment at a time.

If that is the case, why bother writing variables when you could write a character string that contains the current information?
Here's what I mean:

Let's take your example, and make it into a single string for maces and armor types.

//maces
string spikedmaces = "spiked"; // s 
string bronzemaces = "bronze";// b
string ironmaces = "iron";  //i
string silvermaces = "silver"; //a
string icemaces = "ice";// c
string firemaces = "fire";//f 
string goldmaces = "gold";//g 
string diamondmaces = "diamond";//d

//armor
string spikedarmor = "spiked";//s
string bronzearmor = "bronze";//b
string ironarmor = "iron"; //i
string silverarmor = "silver"; //a
string icearmor = "ice"; //c
string firearmor = "fire";//f
string goldarmor = "gold";//g 
string dimondarmor = "diamond";//d

Okay. Those comments are the character representations for those items.
Now:

char equip[2]; //Character equipment array. 0 is weapon; 1 is armor

Suppose you're blinged out with a diamond mace and gold armor. When you want to save, you do the following:

equip[0] = 'd'; //thus making your weapon a diamond mace
equip[1] = 'g';//this is your golden armor

And you save the equip array.

When you load the game, you then parse the input information. Based on the character contents of the string, you can equip yourself without storing huge numbers of variables.

do you know a way that i could just do it variable by variable like if i was just going to save just one variable at a time?and then load it couldyou do like a whole example of like saving just a "money" variable?

It's called a struct or class. But if you don't mind me saying, your implementation, while straightforward, isn't very efficient.

You're going to have to write this stuff as structures, then have it saved in binary, using ofstream and write. It's got its appeals...

Here's a quick example:

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

struct example{
char name[40];
int potions;
};

int main()
{  
  struct example hero; //declares instance of struct type 'example' called 'hero'.
  strcpy(hero.name, "Leroy Jheeenkins");
  hero.potions = 5;


//write data

  ofstream save_1("savefile", ios::out|ios::binary);
  if(!savefile) //Couldn't open save file.
  {
     cout<< "Save failed."<<endl;
     return 1;
  }
  save_1.write((char *) &hero, sizeof(struct example)); //writes entire struct to file.
  save_1.close(); //closes file stream
  return 1;
}

do you know a way that i could just do it variable by variable like if i was just going to save just one variable at a time?and then load it couldyou do like a whole example of like saving just a "money" variable?

See my last post for an edit. To get the info out of the file, you have to use ifstream and read.

ifstream load_1("savefile", ios::in | ios::binary);
if(!load_1)
{
cout<< "Cannot load file"<<endl;

return 1;
}
load_1.read((char *) &hero, sizeof(struct example)); //loads the saved struct.
cout<<hero.name<<endl;
cout<<"Number of potions: " << hero.potions<<endl;
load_1.close(); 
return 0;
}

Edit: This lets you use the hero struct and all its information until the program exits.

That's really the best way to do it simply, but I still think your method is rather awkward and uses a lot of resources it doesn't have to.

yuuuyuyuiuttyi never mind


thx

The struct has to contain the values of the variables you are interested in. The file should be binary, which would likely make it unreadable to you. But if you load the file, you should be able to access the information from the struct as you saved it.

This is why I reccomend you use a more condensed version of storing information. Your program needs to know that a 'd' in the mace slot stands for 'diamond mace', but the save file doesn't. It just wastes space and time to write out 'diamond mace' in the file.

The two examples I gave should be able to work together to save, then load information. You just need to take out the return 0 from the saving example before you put the code together.

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.