Try stop = temp.empty()
instead. getline
should not contain any new-line characters. An empty line should result in an empty string.
Also, Charles is correct, your while condition is incorrect, use while( !stop && ind < 20)
. The way you have it written the user needs to enter 20 values, and an empty line. Charles' change says to break when either condition is met (not both).
For the sake of completeness, here's the proposed new code:
bool stop = false;
int ind = 0;
while( !stop && ind < 20 ){
cout << "Enter name #" << (ind+1) << ":";
string temp;
getline(cin, temp);
if(temp.empty()) {
stop = true;
} else {
names[ind] = temp;
}
ind++;
}
Personally, I would write the code as follows:
vector<string> names;
for(int ind = 0; ind < 20; ind++) {
cout << "Enter name #" << (ind + 1) << " (blank to stop): ";
string name;
getline(cin, name);
if(name.empty() || cin.eof()) {
break;
}
names.push_back(name);
}
cout << "Read " << names.length() << " names before empty line detected." << endl;