使用功能从文件输出

时间:2019-02-03 15:35:41

标签: c++ visual-studio

标题说明了一切

这是我的代码: 我有一个叫做House的类,在其中定义值。

class HOUSE
{
public:
    int id;
    string 1;
    string 2;
    string 3;
    int an;


};

template<class Type>
class table
{
public:

    vector<Type> V;
    //double inceput;
    //double sfirsit;
    //int comparatii;
    //int interschimbari;   
public:
    table();
    void print();
    void liniar();
};

template<class Type>
table<Type>::table()
{
    ifstream file("file.txt");
    ifstream file1("file1.txt");

    if (file.fail() || file1.fail())
    {
        cerr << "Eroare la deschiderea fisierului!" << endl;
        _getch();
        exit(1);
    }

    HOUSE* value = new HOUSE;

while (!file.eof() || file1.fail())
{
    file >> value->id;
    file >> value->tara;
    file >> value->brand;
    file >> value->culoare;
    file >> value->an;

    this->V.push_back(*value);
}


file.close();

}

值的打印功能

template<class Type>
void table<Type>::print()
{

    cout << endl << setw(50) << "AFISAREA DATELOR" << endl;
    cout << setw(5) << "Id" << setw(15) << "1" << setw(20) << "2" << setw(17) << "3" << setw(20) << "an" << endl << endl;
    for (int i = 0; i < this->V.size(); i++)
    {
        cout << setw(5) << this->V.at(i).id << setw(15)
            << this->V.at(i).1<< setw(17)
            << this->V.at(i).2<< setw(17)
            << this->V.at(i).3<< setw(25)
            << this->V.at(i).an << endl;
    }
    cout << endl << "Dimensiunea tabelului  n= " << V.size() << endl;

}


{
        file >> value->id;
        file >> value->1;
        file >> value->2;
        file >> value->3;
        file >> value->an;

        this->V.push_back(*value);
    }


    file.close();

}

主要

int main() {

    table<MOBILE>* file = new table<MOBILE>();
    table<MOBILE>* file1 = new table<MOBILE>();

 file ->print();    
 file1 ->print();

这是要求的完整代码。 需要使其以某种方式打印来自file1和file2的数据。

如果调用正确,则问题是idk。因为      文件-> print();
     file1-> print(); 两者仅从文件中打印数据     完全没有错误

1 个答案:

答案 0 :(得分:0)

您的代码有很多错误。但我将忽略该问题,仅回答我认为是您的实际问题。

您需要两个table对象,其中一个从file.txt读取,另一个从file1.txt读取。为此,您应该将文件名传递到table::table构造函数中,以便它知道要读取哪个文件。像这样

template<class Type>
class table
{
    ...
public:
    table(const char* filename); // constructor takes filename parameter
    ...
};


template<class Type>
table<Type>::table(const char* filename)
{
    ifstream file(filename); // open filename
    if (file.fail())
...


int main() {

    table<MOBILE>* file = new table<MOBILE>("file.txt"); // read from file.txt
    table<MOBILE>* file1 = new table<MOBILE>("file1.txt"); // read from file1.txt

    file ->print();    
    file1 ->print();
}