I'm asked to accept both a number and a unit, where a unit can be cm, m, in or ft.
For this I have a loop as such
cout << "Please put in a number and its unit.\n";
while (cin >> val >> unit) {
if (val == '|') { break; }
cout << "Please put in a number and its unit.\n";
}
My question is, what is the best way to check the unit string, when it comes to code efficiency as well as readability? Does it make more sense to put a large if statement
if (unit != "cm" && unit != "m" && unit != "in" && unit != "ft") {
cout << "Unit " << unit << " not accepted.\n";
}
Or is it better to have a vector which I initialise with all the units, and then check if it matches any of the units.
if (find(units.begin(), units.end(), unit) == units.end()) {
cout << "Unit " << unit << " not accepted.\n";
}
... where vector<string> units = {"cm", "m", "in", "ft"};
Or is there another way which is much better in terms of efficiency and readability?
I hope this is the right place to ask this question. I thought about code review but it doesn't seem to fit a small question like this.. or does it?