C++存储调用主的次数
C++ store number of times main is called
如何让main((记住每次调用变量时的值?
即如果我第一次运行这个程序,我想mainCallCounter = 0
,但是当我再次被调用时,我希望它增加计数器
#include <iostream>
using namespace std;
static int mainCallCounter = 0;
void outputMainCallCount()
{
cout << "Main was called" << mainCallCounter << "times." << endl;
}
int main()
{
outputMainCallCount();
mainCallCounter++;
return 0;
Main 是程序的入口点。 Main 被调用一次(通常(,当它退出时,您的程序将被拆除并清理。
显然,这意味着局部变量是不够的。您需要某种比应用程序(即文件系统(持续时间更长的外部存储。
你不能。 程序的每次运行都是独立的。 您需要将mainCallCounter
保存在某个地方,并在下次应用程序启动时重新阅读。 将其写入文件是一种选择,另一种可能是Windows注册表或Mac OS X默认系统等。
在 C++ 中声明的所有变量在程序结束时过期。 如果要持久记住程序已运行了多少次,则需要将该数据存储在外部文件中,并在运行程序时对其进行更新。
例如:
#include <iostream>
#include <fstream>
int numTimesRun() {
std::ifstream input("counter.txt"); // assuming it exists
int numTimesRun;
input >> numTimesRun;
return numTimesRun;
}
void updateCounter() {
int counter = numTimesRun();
std::ofstream output("counter.txt");
output << counter;
}
int main() {
int timesRun = numTimesRun();
updateCounter();
/* ... */
}
希望这有帮助!
相关文章:
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- 在C++中调用 MS SQL 存储过程
- opengl-VAO也存储Texrture单元调用
- C++:对象将 lambda 存储到结构中,稍后调用该函数
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 无法调用未来::获取存储在地图中的未来
- 调用一个小函数两次(例如在if条件和主体中)比将结果存储在局部变量中更可取
- 如何防止方法的调用方将结果存储在C++中
- 在地图中存储的类中调用功能
- 虚拟函数在哪里使用 vpointer to vtable 来解析方法调用,非虚拟方法存储在哪里以及如何解析它们?
- 如何使类函数返回数组,然后将其调用并存储在 main 中
- 为同一存储位置调用构造函数两次是否合法?
- 如何从列表中存储的对象调用成员函数
- 多次调用存储过程时C++连接器"Commands out of sync" mySQL
- C++调用存储在映射结构中的函数指针
- 存储并调用具有不同签名的成员函数的unordered_map
- 在递归DP中,通过存储变量来分解递归调用:效率低下
- 如何将函子存储在C 中以后调用
- C++联合如何知道其中存储的类型以及要调用哪个析构函数
- C++存储调用主的次数