【发布时间】:2016-08-30 02:34:47
【问题描述】:
我目前正在使用 C++ 编程。我希望我的程序将一个 int 存储在一个文件中,这样当我关闭程序并再次打开它以获取存储的 int 的值时。我该怎么做?
【问题讨论】:
-
A Tour of C++,第 8 章。
我目前正在使用 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;
}
【讨论】:
#include <fstream> 和 #include <iostream>