patterncppMajor
Reading a collection of strings from the user
Viewed 0 times
readingtheusercollectionfromstrings
Problem
I was trying to write a program that will read a collection of strings from the user, and then end the moment it encounters a
I came across a something like this:
I realized that no matter what, the loop will always end from within its body -- which is the exact result that want.
But there something about piece of code that smells fishy. Are there any better ways?
Another thing to note: I don't want the
".". So then I write a do-while loop.I came across a something like this:
string temp;
vector params;
do
{
cin >> temp;
if (temp == ".")
break;
params.push_back(temp);
} while (temp != ".");I realized that no matter what, the loop will always end from within its body -- which is the exact result that want.
But there something about piece of code that smells fishy. Are there any better ways?
Another thing to note: I don't want the
"." to be pushed onto the vector, hence that's why I added that little if (temp == ".") break; statement.Solution
Don't forget to check the stream status for errors or EOF.
EDIT: You do not necessarily need to invent your own break condition. There's one already — end of file. You can just read strings until you reach it. This way, your program will also work with non-interactive input nicely. To generate an end of file on a terminal, type Ctrl+D on Unix/Linux and Ctrl+Z on Windows.
while (cin >> temp && temp != ".")
{
params.push_back(temp);
}EDIT: You do not necessarily need to invent your own break condition. There's one already — end of file. You can just read strings until you reach it. This way, your program will also work with non-interactive input nicely. To generate an end of file on a terminal, type Ctrl+D on Unix/Linux and Ctrl+Z on Windows.
while (cin >> temp)
{
params.push_back(temp);
}Code Snippets
while (cin >> temp && temp != ".")
{
params.push_back(temp);
}while (cin >> temp)
{
params.push_back(temp);
}Context
StackExchange Code Review Q#2220, answer score: 29
Revisions (0)
No revisions yet.