I am using a menu for the user that uses the numbers 1 and 0 to either enter a name or end the program. I am trying to store a person's name into the a string called Name. However every time a person enters a name, it overwrites the name string.
For example:
Input: Zachary
Output: Zachary
User presses 1 to enter a second name
Input: Lauren
Output: Lauren
The problem I am having is that every time the user enters a name, it overwrites the previous name. I realize I could make string called Name1, Name2, Name3, etc. But to me that is not effective. What if a user wants to enter 200 new names? I would have to make a new variable for each name, what would be an effective way to store several names into different variables without having to manually make a new variable every time a name was entered?
#include <iostream>
#include <string>
usingnamespace std;
int main
{
int answer;
string name;
cout << "Please enter a 1 to enter your name, or a 0 to terminate the program";
cin >> answer;
if (answer == 1)
{
cout << "Please enter your name: ";
cin.ignore();
getline (cin, name);
cout << "Please enter a 1 to enter your name, or a 0 to terminate the program";
cin >> answer;
}
if (answer == 0)
{
cout << "Program terminating"
}
system("Pause");
return 0;
}
I have'nt understood what you're exactly trying to do.
can you give us the Input/Output you want & and the Input/Output you're having?
and please explain more about what you're trying to do.
I am trying to figure out how to declare a variable without having to manually do it. For example if a user wants to enter 10 names, I have to declare 10 separate variables called Name1, Name2, Name3, Name4, Name5.. etc. Is there a work around to this?
You Should Use Arrays Or Vectors.
Although Vectors Are Better Than Arrays.
I'm Not Going To Give You The Code, But I Am Ready To Give You Links To Different Tutorials:
#include <iostream>
#include <string>
#include <vector>
int main()
{
// a container to hold a sequence of names.
// std::vector is the default sequence container.
// see: https://www.mochima.com/tutorials/vectors.html
std::vector<std::string> all_names ;
std::string this_name ;
// quit the loop when an empty string is entered
while( std::cout << "enter a name (or an empty string to end input): " &&
std::getline( std::cin, this_name ) && !this_name.empty() )
{
all_names.push_back(this_name) ; // append this name to the sequence of names
}
if( !all_names.empty() ) // if there is at least one name in the sequence
{
std::cout << "\nthe names are:\n----------\n" ;
for( std::string a_name : all_names ) // for each name in the sequence of names
// http://www.stroustrup.com/C++11FAQ.html#for
{
std::cout << a_name << '\n' ;
}
}
std::cout << "\nProgram terminating\n" ;
}