Site Archive (Complete)
C++ Blog: Walter Brown's cool technique for reading files
C++
void main(void)

Calls, Returns and In-Between.

by Kevin Carlson
SELECTIVE IGNORANCE

Finding the Signal in the Noise

by Andrew Koenig
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




 
INFO-LINK


Related Sites: DotNetJunkies, SD Expo, SqlJunkies