使用函数从文件输出

Output from file using function

本文关键字:文件 输出 函数      更新时间:2023-10-16

标题说明了一切

这是我的代码:我有一个名为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();

这是请求的完整代码。需要让它以某种方式打印文件1和文件2中的数据。感谢

如果调用正确,则问题在于 idk。因为 文件 ->打印();
文件1 ->打印();两者都仅打印文件中的数据 完全没有错误

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

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