2017-10-28 128 views
0

我在for循环中调用下面的函数。在每次迭代中,它会在终端中打印一些数字。数字按距离分开。我想在txt文件中写入数字,以便在程序完全运行后,我可以访问txt文件中的所有数字。这是我的功能:保存在txt中调用for循环的函数的输出(C++)

void printComponents(Components const& cc) 
    { 
    auto id = 0; 
    for (auto& c : cc) { 
     int counter=0; 
     for (auto v : c) 
      { 
      counter ++; 
      } 
     if (counter >1) 
      { 
      std::cout << " " << counter;  
      } 
         } 
    } 

如何在txt文件中保存数字?

+0

莫非你提供我可以投票的完整答案? @Ron –

+0

只需添加另一个参数'std :: ostream&out'并用'out'替换'std :: cout'。 – user0042

+0

@ user0042你的意思是void printComponents(组件const&cc,std :: ostream&out) \t { –

回答

0

您添加其他参数std::ostream& out给你的函数

void printComponents(Components const& cc, std::ostream& out) { 
    // ... 
} 

out

out << " " << counter; 

更换std::cout然后打开一个文本文件,并把它传递给你的函数

std::ofstream file("MyFile.txt"); 
for(...) { 
    printComponents(components,file); 
} 
+0

最后一行中的文件是什么? –

+0

@Monaphys之前构建的std :: ofstream变量。 – user0042

+0

变量'std :: ofstream file'有初始值设定项但不完整类型:std :: ofstream file(“MyFile.txt”); –