Home > Blockchain >  why does this for loop in C using getline() work
why does this for loop in C using getline() work

Time:02-08

I compiled this nested for loop in C . It works, however I don't understand why. Can you please explain the mechanics, and also any information on why the push_back() is allowed in addition to the increment.

for (std::string line; std::getline(in, line); text->push_back(line),   ln) // why does this work? 
{
  // do something
  std::istringstream iss(line); 
  for (std::string word; iss>>word;) // why does this work? 
    // do something
};

text is a shared_ptr<vector<string>>.

CodePudding user response:

Every part of a for loop is optional.

If there is no iteration expression, it nothing is done between the body and testing the condition. In this case that's fine, as the condition does the work.

Any expression that contextually coverts to bool can go in the condition.

You can chain multiple expressions with ,, it will evaluate them left to right and discard the values of all but the last.

CodePudding user response:

The for loop

for (A; B; C)
{
    D;
}

is equivalent to

{
    A;
    while (B)
    {
        D;
        C;
    }
}

and any of A, B, C, and D can be empty.
If those parts are syntactically correct in the while loop, they are also correct in the corresponding for loop.

So your nested loop is equivalent to

{

    std::string line;
    while (std::getline(in, line))
    {
        std::istringstream iss(line); 
        {
            std::string word; 
            while (iss>>word)
            {
                // do something
            }
        }
        text->push_back(line),   ln;
    }
}

Note that the push_back line uses the comma operator for sequencing because the semicolon is the delimiter in the for-loop header.

  •  Tags:  
  • Related