2012-05-29 27 views
0

我有C++程序,其中我運行多次相同的函數,但每次都爲不同的參數值。對於參數的每個值,我想將函數的結果輸出到其名稱包含參數值的文件中。這個怎麼做?這是我想要做的一個例子。在C++中定義循環中的許多輸出文件

for(parameter = 10;parameter<=100;parameter*=10){ 
     ofstream file("file"<<parameter<<".txt", ios::out); 
     function(); 
     file<<result; 
     file.close(); 
}   

回答

4

您可以用ostringstream做到這一點:

for (int parameter = 10; parameter <= 100; paramter *=10) 
{ 
    std::ostringstream name; 
    name << "file" << parameter << ".txt"; 

    // If your library is too old, you have to use 
    // name.str().c_str() 
    // to get the string 
    std::ofstream file(name.str()); // or name.str().c_str() in C++03 

    // ... 
} 
+0

很好的回答。另外,如果Boost是一個選項,請使用'boost :: lexical_cast (參數)'。 – ereOn

+0

@ereOn:我看不出有什麼理由,因爲它使用了類似的技術來引導流(甚至是流)。 – Xeo

+0

錯誤:沒有匹配函數調用'std :: basic_ofstream :: open(std :: basic_ostringstream :: __ string_type,const std :: ios_base :: openmode&)' /usr/include/c++/4.5/fstream: 697:7:note:candidate is:void std :: basic_ofstream <_CharT,_Traits> :: open(const char *,std :: ios_base :: openmode)[with _CharT = char,_Traits = std :: char_traits ,std :: ios_base :: openmode = std :: _ Ios_Openmode] – lovespeed