2012-04-06 34 views
0
struct GPattern() { 
    int gid; 
    .... 
} 
class Example() { 
public: 
    void run(string _filename, unsigned int _minsup); 
    void PrintGPattern(GPattern&, unsigned int sup); 
    .... 
}; 

Eample::run(string filename, unsigned int minsup) { 
    for(...) { // some condition 
     // generate one GPattern, and i want to ouput it 
     PrintGPattern(gp, sup); 
    } 
} 

Example::PrintGPattern(GPattern& gp, unsigned int sup) { 
    // I want to ouput each GPattern to a .txt file 
} 

run用於相應地生成GPattern如何將每個數據輸出到相應的文件?

我想輸出到一個文件是一些文本,重建原始GPattern

我無法預先存儲所有GPattern並輸出它們全部。生成它時,我必須輸出一個GPattern到文件,但我不知道如何實現它。

我曾嘗試在Example類申報ofstream outGPatter("pattern.txt"),但它是沒有用的......

+0

我不想在.txt文件中替換原來的'GPattern' – LoveTW 2012-04-06 07:53:36

+0

我在你的問題中看到很多漏洞。我想我已經爲你解答了這個問題,但我對這些漏洞並不滿意。 – Alexander 2012-04-06 08:17:30

+0

你能告訴我你的想法嗎?謝謝:) – LoveTW 2012-04-06 08:23:42

回答

1

好了,ofstream的是正確的方式去:

Example::PrintGPattern(GPattern& gp, unsigned int sup) { 
    ofstream outGPattern("pattern.txt") 

    outGPattern << gp.gid; << " " << gp.anotherGid << " " .... 

    outGPattern.close() 
} 

你有沒有看着正確的放置pattern.txt?它應該位於.exe所在的文件夾中,或者位於所有.h和.cpp文件所在的文件夾中(至少對於VS)。

如果你想所有模式寫入同一個文件,那麼你需要確保你追加(而不是覆蓋)pattern.txt

ofstream的outGPattern(「pattern.txt」的ios ::應用程序)

因此,您可以先在程序開始時使用ios :: app(清除文本文件)來創建ofstream。然後你用ios :: app構造所有其他的stream來追加新文本,而不是覆蓋它。

或者,你可以使ofstream成爲一個例子的成員變量。然後你只構造一次。

+0

但是在您的方法中,原始數據將被替換,所以我只能得到最新的GPattern。 – LoveTW 2012-04-06 07:37:31

+0

如果你不想替換它,你必須使用ios :: app。進行編輯。 – s3rius 2012-04-06 08:31:20

+0

這是工作!感謝您的回覆! – LoveTW 2012-04-06 08:36:26

1

我認爲你可以使用追加模式,如:

ofstream outGPattern; 
outGPattern.open("GPattern.txt", ios::app); 
+0

感謝您的回覆! – LoveTW 2012-04-06 08:36:13

1

我看到它的方式,你想追加多個GPattern信息,您只需要設置I/O模式ios::app在構造函數中。

struct GPattern { 
    int gid; 
    friend ostream& operator <<(ostream& o, GPattern gp) { 
    return o << "(gid=" << gp.gid << ")"; 
    } 
    ... 
} 

Example::PrintGPattern(GPattern& gp, unsigned int sup) { 
    ofstream fout("pattern.txt", ios::app) 
    fout << gp << endl; 
    fout.close() 
} 
+0

感謝您的回覆!最好:) – LoveTW 2012-04-06 09:15:15