Reputation: 71
string s = Console.ReadLine();
while(s != null)
{
// do something
// ....
s = Console.ReadLine();
}
The code above is to get the input, verify it, process it and then input again, but obviously, s = Console.ReadLine();
is code duplication.
What tricks are there to avoid the duplication?
Upvotes: 3
Views: 405
Reputation: 532053
In Python (where there is no do-while
loop to guaranteed at least one iteration), the trick is to use an infinite loop with an explicit break.
while( true ) // Or whatever evaluates to true unconditionally
{
s = Console.ReadLine();
if (s == null) {
break;
}
// do something
}
Upvotes: 2
Reputation: 9946
depending on language, you can often do something like this:
while (s = Console.ReadLine())
{
...
}
Upvotes: 2