I am in a beginning CS class at my University and my assignment is to write a program that takes a series of restaurants and narrows them down tournament style until you have a single choice (That's not very descriptive, but that's not where my problem lies.)
I am using vectors to store the restaurant names and have written a function so the user can input a restaurant. The function uses push_back to store the new element every time it's called. The problem is, the user input is not getting stored. Here's the code for the function:
int rest_add(vector<string>& r_arr) //r_arr stands for Restaurant Array
{
string r_in; //r_in stores the user input
cout << "Please enter a restaurant name: ";
cin.clear();
getline(cin, r_in);
cout << endl;
string finder = r_in;; // the var finder and the loop following it are there to find if the restaurant the user enters is already in the vector and returns them to the menu if it is.
for(int i = 0; i < r_arr.size(); i++)
{
if(r_arr[i] == finder)
{
cout << "This restaurant is already in the tournament." << endl;
return 0;
}
}
r_arr.push_back(r_in); //Here's where the problem is.
cout << "Restaurant successfully added." << endl;
return 1;
}
I feel like I'm missing something really elementary here, but I've tried it with arrays too and it doesn't work. cout-ing r_in after push_back is called tells me that the var is getting stored properly as a var, just not in the vector. I'm pretty burned out on this one and any help would be appreciated.
Thanks for the input. I didn't even notice that about the finder var.
Here's the main function where the vector is declared and the add function is called.
int main()
{
vector<string> restaurants; //Here's where the vector is declared.
srand(time(0)); //part of the assignment requires me to randomly reshuffle the elements in the array, that's what that's here for.
int menu_choice;
menu_choice = menu();
if(menu_choice == 1)
{
print_array(restaurants, restaurants.size());
main();
}
elseif(menu_choice == 2) //this is where the add function is called.
{
rest_add(restaurants);
cout << restaurants.size() << endl; // I added this line for debugging.
main();
}
etc.
}
returning the size after the function call returns 1 every time.
EDIT: Okay, I think I've got it for those of you Googling this. When I call back the main function it re-initializes my vector as empty. The easiest fix that would be to make it a global variable, but I know that's discouraged. Any other suggestions?
The easiest solution would be to not recall the main() function. Find a different way to control the flow of the main function. Just don't re-call it. Not a good idea.
The program shouldn't even compile with the recursive call to main(). In a C++ program main() can not be called by any function, including main(). This is prohibited by the standard.