Hello Tomoecchi,
There are many ways to write a for loop. In the beginning you are taught:
for (int i = 0; i < 10; i++)
and this would be the basic construct of the for loop. After this what you put in a for loop and how you use it will depend on what you need to do as long as you follow the basic construct of its construction.
In
lastchance's example:
1 2
|
for ( int data; getline( fileData >> ws, dummy ) && fileData >> data; )
stuff.push_back( data );
|
for ( int data; getline( fileData >> ws, dummy ) && fileData >> data; )
He defines the "int" "data" to read the number in the file. Which becomes a local variable to the for loop. The middle section is where most of the work is done.
for ( int data; getline( fileData >> ws, dummy ) && fileData >> data; )
First the "getline" is reading the first line of the file, Where the input comes from, it is reading and skipping any leading white space, whatever it may be, and putting what is left in the variable "dummy".
Whether you use formatted or unformatted input and a variable called "dummy" or "junk" to get by something that you do not need this comes in very handy at times.
I am not sure why
lastchance used the "std::ws" here. I am thinking that:
1 2
|
for ( int data; getline( fileData, dummy ) && fileData >> data; )
stuff.push_back( data );
|
should work since all you are dong is getting by the first line. But I have not tried that yet.
The (&&) and what is to the right of it reads the number that you actually want.
Since the middle part of the for loop is an (&&) both sides have to be true for the loop to continue. Here the "getline" will more likely set the "eof" bit on the file stream and cause the condition to become false and end the while loop.
In his example the 3rd part is empty because there is nothing to do, so the middle part keeps repeating until "eof" is reached.
Although I understand the for loop forgive me and bear with me if I got something wrong or I have misunderstood something. If there is any part that youstill do not understand let me know and I will work on it.
Andy