2013-10-09 23 views
0

我該如何讓main()在每次被調用時記住一個變量的值?C++ store調用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; 
+2

將編號存儲在文件中。讓程序讀取它? –

+0

將該號碼保存到磁盤。 – Chad

回答

0

當程序結束時,所有以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(); 

    /* ... */ 
} 

希望這有助於!

1

你不能。程序的每次運行都是獨立的。您需要在某處保存mainCallCounter,並在下次啓動應用程序時重新閱讀。將它寫入文件是一種選擇,另一種可能是Windows註冊表或Mac OS X默認系統等。

2

Main是您程序的入口點。 Main被調用一次(通常),當它退出時,你的程序被拆除並清理乾淨。

顯然這意味着局部變量將不足。您需要某種比您的應用程序(即文件系統)更長久的外部存儲。

+0

'main'在C++中被調用一次,句點。 –

+0

@CarlNorum:對嗎? 'int main(){main(); }' –

+0

這是C++標準禁止的。 「函數'main'不能在程序中使用。」 –