Reputation:
I have an issue where I am creating a basic text user interface. In order to keep the text interface looping, I call main() until the user chooses to quit by pressing 0.
However, this recreates my LinkedList list, which I would like to keep as a permanent. I understand that it is bad practice to have it as a global variable, so how can I get around this issue?
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;
}
Upvotes: 0
Views: 49
Reputation: 2740
It is probably not a good idea to use recursion to do this task. If you want it to repeat you are probably better off with a while loop. http://msdn.microsoft.com/en-us/library/2aeyhxcd.aspx
While(true) will loop as long as the statement (true) is true. Aka forever. You could also do something like while(choice != 0)
though that would require a slight rework of your code.
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;
}
Upvotes: 1