为什么这个 for 循环在 C++ 中使用 getline() 工作

why does this for loop in C++ using getline() work

我用 C++ 编译了这个嵌套的 for 循环。它有效,但我不明白为什么。您能否解释一下机制,以及关于为什么除了增量之外还允许 push_back() 的任何信息。

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
};

textshared_ptr<vector<string>>.

for 循环的每个部分 is optional

如果没有迭代表达式,则在正文和测试条件之间什么都不做。在这种情况下很好,因为条件起作用了。

任何上下文转换为 bool 的表达式都可以进入条件。

您可以使用 , 链接多个表达式,它将从左到右计算它们并丢弃除最后一个以外的所有值。

for 循环

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

相当于

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

并且 ABCD 中的任何一个都可以为空。
如果这些部分在 while 循环中在语法上是正确的,那么它们在相应的 for 循环中也是正确的。

所以你的嵌套循环相当于

{

    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;
    }
}

请注意,push_back 行使用逗号运算符进行排序,因为分号是 for-loop header.

中的分隔符