2014-04-16 52 views
0

首先,我爲我的糟糕英語感到抱歉。如何打印從不同功能的文本文件中讀取的數據

我想問的是如何打印從不同功能的文本文件中讀取的數據。

load()函數定義如下。

void Picture::load(string filename) throw(string) 
{ 
int x,y; 
string line; 

fstream infile(filename.c_str(), fstream::in); 

if (infile.is_open()) 
{ 
    if (!getline(infile, line)) 
     throw string("Unable to read the first line."); 

    istringstream iss(line); 

    if (!(iss >> height >> width)) 
     throw string("First line does not consist of two integers."); 

    picture = new char*[width]; 

    for (x=0; x<width; x++) 
     picture[x] = new char[height]; 

    for (y=0; y<height; y++) 
    { 
     getline(infile,line); 

     if (line.length() < width) 
      throw string("Line "+convertInt(y+1)+" in picture has an incorrect width."); 
     else 
      for (x=0; x<width; x++) 
       set(x,y,line[x]); 
    } 

    infile.close(); 
    } 

    else throw string("Unable to open file"); 
} 

void Picture::print() 
{ 
    // This function will print the data read on load function 
} 

如何將這兩個函數關聯起來以便加載和打印?

對不起,如果這個問題之前已經問過。

回答

0

數據存儲爲你的類的私有成員:

private std::string data; 
void loadAndPrint::load() 
{ 
    in_file.open("infile.txt"); 
    in_file >> data; 
} 
void loadAndPrint::print() 
{ 
    ofstream out_file("outfile.txt"); 
    if(!out_file.is_open()) throw myError; 
    out_file << data; 
} 
+0

我有一個私有成員'字符** picture'。你可以參考我最近編輯的關於'load()'函數的問題嗎? – user3538277

0

您可以通過引用傳遞的fstream到第二功能。這使您不必製作私有變量。

編輯:

沒有能夠看到整個班級,我不能肯定,但它看起來像你的老師希望你使用NTCAs此作業。如果不只是給你一個完整的答案,看看這篇文章,看看它是否回答你的問題:

http://www.cplusplus.com/doc/tutorial/ntcs/

+0

嗯,實際上這個任務,我的講師已經定義了加載函數和不能改變的類。閱讀我最近編輯的問題。我包含了我無法改變的'load()'函數。 – user3538277

+0

因此,唯一可以改變的是打印功能和課外作業? – GGMG

+0

是的。我需要做的是完成定義的方法。我在打印加載的文本時遇到問題。 – user3538277

相關問題