The first problem I can spot in your code is, that you provide a fixed sized array of string names[3];
to store an unknown number of inputs from the user. That certainly won't work.
To fix this use a container that can use an "arbitrary" number of std::strings
;
std::vector<std::string> names;
Having this you can just use something like
std::vector<std::string> names;
std::string name;
while(cin >> name) {
names.push_back(name);
}
The problem still left is how you could end this loop.
There are several options:
Let the user use one of CTRL-D or CTRL-Z (<- subtle link)
Ask them to enter a special value like quit
, exit
, -1
to end inputting
- Track it down to a second level to process ENTER. Use
std::getline()
parse all the words using a std::istringstream
or break
, when getline()
reads an empty result.
Let's analyze these:
Is a bad choice, because it's operating system dependent and asks the user to do relatively complicated actions.
Restricts the possible inputs, and there's a method needed to escape inputs of quit
, exit
or alike.
Empty input like retrieved from a simple additional hit of the ENTER key is probably the most intuitive you can offer to the user.
As a solution following my proposal in 3.:
std::string line;
std::vector<std::string> names;
while ( getline( cin, line)) {
if(line.empty()) {
// end input condition
break;
}
std::istringstream iss(line);
std::string name;
while(iss >> name) {
names.push_back(name);
}
}