C++存储调用主的次数

C++ store number of times main is called

本文关键字:存储 调用 C++      更新时间:2023-10-16

如何让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();
    /* ... */
}

希望这有帮助!