2011-10-10 57 views
0

您好我想寫的文字處理文件:ofstream的ofstream的錯誤

#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <string> 
#include <cstring> 
#include <stdlib.h> 

using namespace std;  


void init_log(ofstream* data_file, ofstream* incl_file, string algo){ 
    stringstream datafilename; 
    datafilename << "report/data/" << algo << ".txt"; 
    stringstream includefilename; 
    includefilename << "report/include/" << algo << ".tex"; 

    data_file->open(datafilename.str().c_str(), ios::app); 
    incl_file->open(includefilename.str().c_str(), ios::app); 
} 

void write_log(ofstream* data_file, ofstream* incl_file, int size, double timesec){ 
    stringstream tow_data; 
    tow_data << size << " " << timesec << endl; 
    stringstream tow_incl; 
    tow_incl << size << " & " << timesec << " \\\\ \\hline" << endl; 

    *data_file << tow_data.str().c_str(); 
    *incl_file << tow_incl.str().c_str(); 
} 

void close_log(ofstream* data_file, ofstream* incl_file){ 
    data_file->close(); 
    incl_file->close(); 
} 
int main (int argc, const char * argv[]){ 

    double elapsed = 1.0; 
    int test = 10; 

    ofstream* data_file; 
    ofstream* incl_file; 

    init_log(data_file, incl_file, "hello"); 


    write_log(data_file, incl_file, text, elapsed); 


    close_log(data_file, incl_file); 

    return 0; 
} 

當我運行此的XCode告訴我一個壞的exec ACCES來自data_file->open(datafilename.str().c_str(), ios::app);?我在哪裏得到錯誤?

+2

沒有冒犯,但你需要[一本好的C++書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – sbi

+0

這絕對不是一種冒犯,但非常感謝! – Kami

回答

6
ofstream* data_file; 
ofstream* incl_file; 

你已經宣佈這些爲指針,你正在使用他們沒有爲他們分配內存。這是運行時錯誤的原因。

我會建議你做,然後自動的對象,如:

ofstream data_file; 
ofstream incl_file; 

,然後將它們傳遞爲引用類型:

void init_log(ofstream & data_file, ofstream* incl_file, string algo){ 
        //^^^ reference 
} 

void write_log(ofstream & data_file, ofstream* incl_file, int size, double timesec){ 
        //^^^ reference 
} 

void close_log(ofstream & data_file, ofstream* incl_file){ 
        //^^^ reference 
} 
2

具有指向流真奇怪。問題是你從來沒有初始化這樣的指針,但仍嘗試訪問它們。您錯過了幾個new s。