Question:
C++ Prog: How can I save variables for next time I run the program?
Chris
2010-05-31 01:12:54 UTC
I'm making a simple game using C++. Is it possible to do the following?

1. Ask the user to pick a file name
2. The program then creates a file using that name
3. The program saves the variables (and their values) onto that file.
4. The user can close the program and then later run the program from the beginning and input the file name to continue their progress in the game

If this possible, can someone please help me how to do this? If it's not possible, how can I let the user save their progress? Thanks so much for any help.
Three answers:
Tizio 008
2010-05-31 02:06:32 UTC
the most simple way is to use a ascii based file, you simply output the data you want to store one per line, as in

file << value << endl;



then you can read them with something like

rfile >> value;



this works for "primitive" values while for object you need marshalling / serialization and likely you need a binary format.... or to code a littel bit more for reloading the values.

http://en.wikipedia.org/wiki/Marshalling_(computer_science)
D
2010-05-31 01:23:41 UTC
First of all, nobody is going to help you cheat on your homework. If you have questions you should ask your teacher, not only is it their job but that way you'll have an idea of what they expect.



A few things to consider:

-You'll need to learn how to accept user input. Your textbook should have a chapter explaining how to do that, or lookup "cin" in the index.

-You'll need to learn how to write to a file and read to a file. Your textbook should have a chapter explaining how to do that.

-Once you know how to do that, you need to figure out how you're going to predictably read and write your variable values to a file (know what's what in the file). An easy way could be to write each variable value on a separate line. You'll know which variable's value you put on the 1st line, which on the 2nd line, etc.
?
2016-12-04 14:07:52 UTC
void important() { int a,b; //declare 2 variables printf (" enter the numbers : " ); scanf ("%d %d", &a, &b); //enter 2 numbers separated via an area printf (" previously interchanging : n a = %d, b = %d", a , b ); //print previously interchanging a=a+b; b=a-b; a=a-b; printf (" After interchanging : n a = %d, b = %d", a , b ); //print after interchanging getch(); }


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...