在 c++ 中向/从文件中读取写入变量

Read Write Variable to/from file in c++

本文关键字:读取 变量 文件 c++ 中向      更新时间:2023-10-16

我正在尝试让我的c ++程序写入然后从文件中读取变量,但没有成功。代码如下:

#include <iostream>
#include <fstream>
using namespace std;
int f;
int main()
{
ifstream in("variabila.txt");

ofstream fout;
fout.open("variabila.txt");
fout<<f<<endl;
fout.close();
cout << f << endl;
cin >> f;
in >> f;
cout << f << endl;
return 0;
}

你能帮我吗?

关闭文件进行写入后,应打开文件进行读取。

#include <iostream>
#include <fstream>
using namespace std;
const int f = 123;
int main()
{
{
ofstream fout("variabila.txt");
fout<<f<<endl;
}
{
ifstream in("variabila.txt");
int g;
in >> g;
cout << g << endl;
}
return 0;
}