如何打印从不同功能的文本文件中读取的数据

时间:2014-04-16 01:32:03

标签: c++

首先,我很抱歉我的英语不好。

我想问的是,如何打印从不同功能的文本文件中读取的数据。

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
}

如何关联这两个功能,以便我可以加载和打印?

很抱歉,如果之前有人问过这个问题。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

您可以通过引用传递fstream到第二个函数。这使您不必创建私有变量。

编辑:

无法看到整个班级,我无法确定,但看起来您的教练希望您使用NTCA进行此项任务。如果不给您完整的答案,请查看本文,看看它是否回答了您的问题:

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

相关问题