Reputation: 35
Say I create a vector whose size is not yet denoted and whose elements are strings. I want to input strings into this vector using a for loop and cin
. Then, when the user has finished inputting the strings, I want the for loop to terminate.
I know two ways of doing this. The input stream can be terminated using Ctrl + Z on Windows or Ctrl + D on Unix. I can also use an if statement with a break
, so that on the input of a certain string such as "end"
, the loop terminates.
My implementation would be the latter of the two:
vector<string> words;
for(string temp; cin >> temp;)
{
if(temp == "end")
{break;}
else
{words.push_back(temp);}
}
So, for the input foo bar
the loop won't terminate, but for the input foo bar end
the loop terminates (and for foo end bar
the loop would terminate such that the vector contains only the string "foo"
).
Is the above implementation the best way of doing it? Would it be more efficient to just use Ctrl + Z or Ctrl + D as that avoids having to go through an if statement in each iteration?
This would be different if we instead had a vector whose elements were of type int
, as the user could enter anything that isn't an integer in order to terminate the loop. But in the case of strings, anything the user enters can be considered a string.
I am working through chapter 4 of the book by Bjarn Stroustrup, "Programming - Principles and Practice using C++".
Upvotes: 2
Views: 228
Reputation: 490488
I'd prefer to loop header to reflect the expected exit condition(s), so if you want to read until the user enters end
, I'd prefer to have that test in the condition of the loop:
for (std::string temp; std::cin >> temp && temp != "end"; )
words.push_back(temp);
As far as "efficiency" goes, in a case like this it's almost certainly irrelevant. Concentrate on making the code simple and readable. Optimize only when measuring shows you need to.
Upvotes: 7