【问题标题】:How can I store a variable in another file?如何将变量存储在另一个文件中?
【发布时间】:2016-08-30 02:34:47
【问题描述】:

我目前正在使用 C++ 编程。我希望我的程序将一个 int 存储在一个文件中,这样当我关闭程序并再次打开它以获取存储的 int 的值时。我该怎么做?

【问题讨论】:

标签: c++ file save


【解决方案1】:

你可以使用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;
}

【讨论】:

  • 错误:“变量 std::fstream fs 具有初始化程序但类型不完整 std::fstream fs("data.txt");
  • @PanagiotisIatrou 您需要添加包括:#include &lt;fstream&gt;#include &lt;iostream&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2021-04-22
  • 1970-01-01
相关资源
最近更新 更多