Suppose I want to read lines from the console and put those into a container until the user enters a blank line. I do not want that blank line ending up in my container, though. I can think of five different solutions:
a) break from loop
std::vector<std::string> container;
for (; ;)
{
std::string line = get_input();
if (line.empty()) break;
container.push_back(line);
}
b) read before loop and inside loop
std::vector<std::string> container;
std::string line = get_input();
while (!line.empty())
{
container.push_back(line);
line = get_input();
}
c) read as part of loop condition, assignment version
std::vector<std::string> container;
std::string line;
while (!(line = get_input()).empty())
{
container.push_back(line);
}
d) read as part of loop condition, sequence version
std::vector<std::string> container;
std::string line;
while (line = get_input(), !line.empty())
{
container.push_back(line);
}
e) read too much, remove it after loop
std::vector<std::string> container;
std::string line;
do
{
line = get_input();
container.push_back(line);
}
while (!line.empty());
container.pop_back();
So, which solution would you prefer, and why? Which would be the easiest to understand for a beginner?
I prefer (a). simple and reads quite naturally.
(b) repeats the line that gets the input.
(c) and (d) both use syntax that may be confusing to beginners (specifically, the comma not within a
forstatement or a definition, and assignment within a conditional). I’d probably prefer (c) over (d) though.(e) is… inefficient. What if that last
push_backcaused a reallocation?