首页 > 解决方案 > 使用函数从文件输出

问题描述

标题说明了一切

这是我的代码:我有一个名为 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();
文件1->打印();都只打印文件中的数据 完全没有错误

标签: c++visual-studio

解决方案


您的代码有很多错误。但我会忽略这一点,只回答我认为是你的实际问题。

您需要两个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();
}

推荐阅读