英文:
How can i keep the value of a variable even after the programm ends?
问题
我试图在程序运行结束后仍然使用一个变量值...我想要使用这个变量来存储更多的账户,但每次我按下F9都会丢失该值,并且从0重新开始;我希望在第一次按下F9后将该值增加1,而我创建的记事本中要包含每个账户...我不确定我是否表达清楚,但也许有人可以帮助我。
英文:
I am trying to use a variable value even after the programm runs out....I want to store more accounts using this variable, but everytime i press F9 it lose the value, and start again from 0; I want after the first F9 to increase the value by 1, and the notpad I create with accounts i want to has every account...I am not sure I make myself understandable but maybe someone can help me.
答案1
得分: 2
@André Cascais 和 @ds4940 是正确的。在您的程序中包含 fstream 库,并使用 ifstream 读取文件和 ofstream 写入文件。您还可以使用 fstream 同时进行读取和写入。
文本文件示例:
#include <iostream>
#include <fstream>
int main()
{
std::ifstream in_file{"test.txt"};
// 检查文件是否已打开
if (!in_file)
{
std::cerr << "无法打开 test.txt\n";
return 1;
}
std::string str;
int x{};
double y{};
// 从文件中读取值
in_file >> str >> x >> y;
in_file.close(); // 关闭文件
// 截断 test.txt
std::ofstream out_file{"test.txt"};
if (!out_file)
{
std::cerr << "无法打开 test.txt\n";
return 1;
}
// 显示数据
std::cout << str << " " << x << " " << y << std::endl;
// 写入新数据
out_file << str << " " << x + 1 << " " << y + 1 << std::endl;
out_file.close(); // 关闭文件
return 0;
}
此示例假定程序运行时您已经拥有文件。如果要按行读取,请使用 getline 方法。希望这对您有所帮助!
英文:
@André Cascais and @ds4940 are right. Include the fstream library in your program and use ifstream to read a file and ofstream to write to a file. You can also use fstream to do both reading and writing.
Example with text file:
#include <iostream>
#include <fstream>
int main()
{
std::ifstream in_file{"test.txt"};
// check if the file opened
if (!in_file)
{
std::cerr << "Unable to open test.txt\n";
return 1;
}
std::string str;
int x{};
double y{};
// read the values from file
in_file >> str >> x >> y;
in_file.close(); // close the file
// truncate test.txt
std::ofstream out_file{"test.txt"};
if (!out_file)
{
std::cerr << "Unable to open test.txt\n";
return 1;
}
// display data
std::cout << str << " " << x << " " << y << std::endl;
// write new data
out_file << str << " " << x + 1 << " " << y + 1 << std::endl;
out_file.close(); // close the file
return 0;
}
This example assumes you already have the file when the program runs. If you want to read by line use the getline method. Hope this helps!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论