如何控制是否打印空间?

时间:2015-08-24 07:14:13

标签: c++

我无法解释以下代码的含义。有人可以对此有所了解。在以下代码中,bool变量firstword控制空间的打印。但是,由于它是真的,第二个while循环中的if语句永远不会转到else语句来打印空格。我的解释是正确的还是我读错了?感谢

void word_transform(ifstream &map_file, ifstream &input)
{
  auto trans_map = buildMap(map_file); // store the transformations
  string text;
  while(getline(input,text)){
      istringstream stream(text);
      string word;
      bool firstword = true;
      while(stream>>word){
         if(firstword)
             firstword = false;
         else
             cout<<" ";
      }
      cout<<endl;
   }
}

1 个答案:

答案 0 :(得分:0)

 bool firstword = true;
      while(stream>>word){
         if(firstword)
             firstword = false; // <<<<<<<<<<
         else
             cout<<" ";
     }

第一次迭代:firstword is true;将firstwort设置为false

第二次迭代:执行firstword is false; else语句