1

我的程序的主要功能显示一个开关菜单。当输入选项 1 时,会调用一个函数来“洗牌”一组“卡片”。改组完成后,该函数通过调用 main() 将程序返回到开头,从而再次显示菜单。

我遇到的问题是菜单的选项 4 将洗牌后的数组写入文件。但是在洗牌后重新启动程序时,数组数据丢失,因此输出的文件都是垃圾文件。有没有办法在不丢失数据的情况下重新启动 main() ?

我在上课,我可以使用的工具有限,所以只能接受最基本的代码。基本上,我正在寻找类似 goto 但更安全的东西(顺便说一下,goto 在这个类中也是禁止的)。

4

4 回答 4

7

It's actually not a good idea for a C++ program to call its own main function. In fact, this leads to undefined behavior, which means that you have no guarantees about the behavior of the program. It could crash, or proceed with corrupt data, or format your hard drive, etc. (that last one is unlikely, though).

I think that this reflects a more fundamental problem with how your program works. If you want data to persist across functions, you need to place that data somewhere where it won't get clobbered by other functions. For example, you could put the data in the heap, then pass pointers to the data around. Or, you could define it as a local variable in main, then pass it down into functions and have those functions return when they're done. You could also consider making objects representing the data, then passing those objects across the different functions.

Without seeing your code, I doubt I can give a more specific answer than this. When designing programs, keep the data flow in mind. Think about what data needs to go where and how you're going to get it there.

Hope this helps!

于 2013-02-08T03:00:37.737 回答
2

你为什么要main递归调用(顺便说一句,这是标准禁止的)?只需使用循环(例如 a do... while)来重复需要重复的部分,main将不得重置的变量(及其初始化)保留在循环之外。

于 2013-02-08T03:02:34.073 回答
1

main()函数不应被递归调用。
您可以将游戏循环封装到一个while()函数中。

看看这个例子:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    bool exitGame = false;
    // Game Loop
    while(!exitGame) {

        // Display menu
        cout << "Menu :" << endl;
        cout << "- Shuffle :  press 1" << endl;
        cout << "- Option 2 : press 2" << endl;
        cout << "- Option 3 : press 3" << endl;
        cout << "- Exit     : press 4" << endl;
        cout << "Enter your choice : ";

        // Get user input
        string choosenValue;
        cin >> choosenValue;

        cout << endl;

        // Process user input
        if (choosenValue == "1") {
            cout << "You selected 'Shuffle'." << endl;
            // Do cool stuff here !

        } else if (choosenValue == "2") {
            cout << "You selected 'Option 2'." << endl;
            // Do cool stuff here !

        } else if (choosenValue == "3") {
            cout << "You selected 'Option 3'." << endl;
            // Do cool stuff here !

        } else if (choosenValue == "4") {
            cout << "You selected 'Exit'." << endl;
            exitGame = true;

        } else {
            cout << "Wrong value." << endl;
        }
        cout << endl;
    }

    return EXIT_SUCCESS;
}
于 2013-02-10T09:56:24.057 回答
0

Move main body to another function 'myMain' and call it insteadOf main.

于 2013-02-08T03:00:29.563 回答