如何将变量存储在另一个文件中?
How can I store a variable in another file?
我目前正在用 C++ 编程。我希望我的程序将一个 int 存储在一个文件中,以便在我关闭程序并再次打开它时获取存储的 int 的值。我该怎么做?
您可以使用 std::fstream:
#include <fstream>
#include <iostream>
int myint;
int main() {
// when entering app:
std::ifstream fs("data.txt");
if ( fs ) {
fs >> myint;
}
fs.close();
std::cout << myint;
myint++;
// when exiting app:
std::ofstream fs2("data.txt");
fs2 << myint;
}
我目前正在用 C++ 编程。我希望我的程序将一个 int 存储在一个文件中,以便在我关闭程序并再次打开它时获取存储的 int 的值。我该怎么做?
您可以使用 std::fstream:
#include <fstream>
#include <iostream>
int myint;
int main() {
// when entering app:
std::ifstream fs("data.txt");
if ( fs ) {
fs >> myint;
}
fs.close();
std::cout << myint;
myint++;
// when exiting app:
std::ofstream fs2("data.txt");
fs2 << myint;
}