October 05, 2006
Walter Brown's cool technique for reading files
How do you write a loop to do something with each line of a file? One common way:
string s;
while (getline(file, s)) { /* do something */ }
This technique has the small disadvantage of separating the definition of s from the loop that uses it, and therefore of having the value of s hang around longer than needed.
Walter Brown, from the Fermi National Accelerator Laboratory and a member of the C++ committee, once suggested to me the following elegant technique:
for (string s; getline(file, s);) { /* do something */ }
Once seen, this technique seems obvious; but good ideas often seem that way.
Posted by Andrew Koenig at 04:15 PM Permalink
|