簡體   English   中英

使用函數從文件輸出

[英]Output from file using function

標題說明了一切

這是我的代碼:我有一個名為 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 -> 打印(); 兩者都只從文件中打印數據根本沒有錯誤

你的代碼有很多錯誤。 但我會忽略這一點,只回答我認為是你的實際問題。

您需要兩個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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM