C++ - 循环主重置对象



我在创建基本文本用户界面时遇到问题。为了保持文本界面循环,我调用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;
}

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

while(true) 只要语句 (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;
}

相关内容

  • 没有找到相关文章

最新更新