我对编程比较陌生,因为我刚刚在学校开始学习。我打算制作游戏,但我无法弄清楚如何将数据输入或其他值存储到计算机的内存中,然后在以后的运行中再次使用它们。甚至可以这样做吗?
P.S。我使用c ++,如果你能通过c ++解释它会很棒。
答案 0 :(得分:1)
由于您不熟悉编程,因此保存数据以便在以后运行中使用的好地方是将数据写入文本文件,然后在以后运行时从文件中加载该数据。这将为您提供一些文件输入/输出的良好体验(这对于了解任何编程语言非常有用,而不仅仅是C ++)。这里有一个关于文件i / o的好教程,值得一试作为起点:http://www.cplusplus.com/doc/tutorial/files/
对于基本演示,我们假设您要保存播放器名称和分数:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
// player information we want to write out
string name = "player1";
int points = 1234;
int turn = 10;
ofstream fout; // I use fout as shorthand for "File OUTput"
fout.open("file1.txt"); // opens a file named 'file1.txt' for writing
// write the data to the file
fout << name << ' ' << points << ' ' << turn << endl;
fout.close(); // don't forget to close the file output stream
// now let's open the file to read in the data
ifstream fin; // I use fin as shorthand for "File INput"
fin.open("file1.txt");
string namereadin = "";
int pointsreadin = -1;
int turnreadin = -1;
// now let's read in the data. Since we know what order we wrote the info
// to file in, we can read it in using that same order
fin >> namereadin >> pointsreadin >> turnreadin;
// now just to show that we read the input correctly, let's output it to the screen
cout << namereadin << " " << pointsreadin << " " << turnreadin << endl;
}
您最终还想使用try-catch块进行错误处理。