C ++ - 循环主要重置对象

时间:2014-11-25 21:26:27

标签: c++ object main

我遇到了创建基本文本用户界面的问题。为了保持文本界面的循环,我调用main()直到用户选择按0退出。

但是,这会重新创建我的LinkedList列表,我希望将其保留为永久列表。我知道将它作为全局变量是不好的做法,那么我该如何解决这个问题呢?

int main() {

    int choice, newLatitude, newLongitude;
    string newName;

    LinkedList list;

    cout << "[1] Add a city \n";
    cout << "[2] Display list of cities \n";
    cout << "[0] Exit program \n";
    cin >> choice;
    if (choice == 0) {
        return 0;
    }
    else if (choice == 1) {
        cout << "Enter city name: ";
        cin >> newName;
        cout << "Enter latitude: ";
        cin >> newLatitude;
        cout << "Enter longitude: ";
        cin >> newLongitude;
        City newCity(newName, newLatitude, newLongitude);
        list.addNode(newCity);
    } 
    else if (choice == 2) {
        list.display();
    }
    else {
        cout << "Invalid option, please try again \n";
    }

        main();

    return 0;
}

1 个答案:

答案 0 :(得分:2)

使用递归来执行此任务可能不是一个好主意。如果你想重复它,你可能会更好地使用while循环。 http://msdn.microsoft.com/en-us/library/2aeyhxcd.aspx

只要语句(true)为真,while(true)就会循环。阿卡永远。您也可以执行while(choice != 0)之类的操作,但这需要对代码进行轻微的修改。

int main() {

    int choice, newLatitude, newLongitude;
    string newName;

    LinkedList list;

    while(true)
    {
        cout << "[1] Add a city \n";
        cout << "[2] Display list of cities \n";
        cout << "[0] Exit program \n";
        cin >> choice;
        if (choice == 0) {
            return 0;
        }
        else if (choice == 1) {
            cout << "Enter city name: ";
            cin >> newName;
            cout << "Enter latitude: ";
            cin >> newLatitude;
            cout << "Enter longitude: ";
            cin >> newLongitude;
            City newCity(newName, newLatitude, newLongitude);
            list.addNode(newCity);
        } 
        else if (choice == 2) {
            list.display();
        }
        else {
            cout << "Invalid option, please try again \n";
        }
    }
    return 0;
}