After trying to make a while(bool) loop and it failing because I couldn’t see the contents of the vectors because there was nothing in them, I made a while(true) loop with the intention of breaking out if the user inputs a 0. Here are the important portions of the code.
Edit: Working code, but what does|= mean?
#include "std_lib_facilities.h"
class Name_pairs
{
public:
vector<string>names;
vector<double>ages;
bool test();
string read_names();
double read_ages();
void print();
};
string Name_pairs::read_names()
{
string name;
cout << "Enter name: ";
cin >> name;
names.push_back(name);
return name;
}
double Name_pairs::read_ages()
{
double age;
cout << "Enter corresponding age: ";
cin >> age;
ages.push_back(age);
cout << endl;
return age;
}
void Name_pairs::print()
{
for(int i = 0; i < (names.size()-1) && i < (ages.size()-1); ++i)
cout << names[i] << " , " << ages[i] << endl;
}
bool Name_pairs::test()
{
if(ages.empty() || names.empty()) return true;
if(ages.back() = 0 || names.back() == "0"){
return false;}
return true;
}
int main()
{
Name_pairs np;
cout << "Enter names and ages. Use 0 to cancel.\n";
bool finished = false;
while(!finished){
finished |= "0" == np.read_names();
finished |= 0 == np.read_ages();}
np.print();
keep_window_open();
}
If you change the problem and view it upside down it becomes quite simple.
Change your setter methods to actually return the value that was just entered. I also made age a local variable of the method to prevent side effects from creeping :
Then in the loop you can test directly for the returned value :
Since you are setting your exit condition in the main (type 0 to exit) it is preferable to test the exit condition there for consistency.
Is how I see it anyway… code is shorter and easier to understand
Edit I changed the code to reflects comments aem. This way the correct logical operator is used. As for the cascading evaluation it is quite true that if the first answer was 0 then the second question will not even be asked (finished evaluated to true thus the rest of the or statement will not be evaluated) and as such you must be careful of this (if for example you expect both Vectors to always have the same length). However I found that usability wise since the user already stated that he wanted to exit I saw no use in asking him the other question.