How do you save and recall variables to a seperate file that the user can name?
Printable View
How do you save and recall variables to a seperate file that the user can name?
use file-handling
ofstream to write, ifstream to read or fstream for both at the same time.
heres an instant code, not tested thoughCode:#include<iostream.h>
#include<fstream.h>
#incude<conio.h>
int main()
{
ofstream fout;
ifstream fin;
int score;
char fname[13];
clrscr();
cout<<"enter filename : ";
cin.getline(fname,12);
fout.open(fname);
fout<<score;
fout.close();
cout<<"DATA STORED."
getch();
clrscr();
cout<<"THE DATA STORED IN : "<<fname<<" IS :\n";
fin.open(fname);
fin>>score;
cout<<score;
fin.close();
getch();
return 0;
}
Ok, im kind of a newby at C++ programming, can you put some comments in there so I know how to understand it and impliment it in this game im making, its a text-based RPG by the way. At least tell me where it is saving variables to the file and where it is recalling them. Thanks in advance.
Code:#include<iostream.h>
#include<fstream.h> // for file i/o
#incude<conio.h>
int main()
{
ofstream fout; // ofstream opens file in output mode ie for writing
ifstream fin; // opens for reading
int score; // var that we'll store
char fname[13]; //filename
clrscr();
cout<<"enter filename : ";
cin.getline(fname,12); //input the file say - file.txt
score=100;
fout.open(fname); //opens file for writing
fout<<score; //writes the value of score
fout.close(); //closes the file
cout<<"DATA STORED."
getch();
clrscr();
cout<<"THE DATA STORED IN : "<<fname<<" IS :\n";
fin.open(fname); //opens for reading
fin>>score; //reads the score
cout<<score; //displays it
fin.close(); //closes it
// when you open the file 'file.txt' you'll see 100 in it
getch();
return 0;
}
Thanks a bunch :)