簡體   English   中英

使用 fstream C++ 編輯初始化的結構成員

[英]Editing an initialized struct member using fstream C++

我被困在初始化結構成員的代碼中,但我不知道如何在 txt 文件中編輯或刪除它。 (這可能嗎?)因為我正在制作關於處理器和主板的“電腦零件店”。任何提示都表示贊賞。 如果我的代碼不干凈也很抱歉,我是初學者。

    #include<iostream>
    #include<string>
    #include<fstream>
    
    const int size = 5;
    
    struct Computer
    {
        string processor[size];
        string motherboard[size];
    };
    
    struct Prices
    {
        double proc_prices[size];
        double mboard_prices[size];
    };
    
    void display_proc(struct Computer comp, struct Prices price);
    
    int main(){
        int chosen_proc, chosen_moth;
        Computer computer = {
            {"1. Asus Prime A320M-K AMD AM4 uATX MotherBoard with LED lighting, DDR4 3200MHz, 32Gb/s M.2, HDMI, SATA 6Gb/s, USB 3.0","2. MSI H410M-A PRO LGA 1200 Supports 10th Gen Intel Core and Pentium Gold / Celeron processors"}, // processsor array init
            {"1. Intel Pentium Dual Core G2030 3.0Ghz 3MB Cache LGA1155 22nm Processor", "2. Intel Core i3-7100 Processor (3M Cache, 3.90 GHz)"} // motherboard array init 
        };
        Prices all_prices = {
            {2499, 5999},
            {2999, 3999}
        };
        system("Color 0A"); // this is just a design only i'm testing it
        
        ofstream proc1("processor.txt", ios::app);
        ofstream mother1("motherboard.txt", ios::app);

    cout <<"Choose your Processor!" << endl;
    if(proc1.is_open()){  
        display_proc(computer, all_prices);
        proc1.close();//file close  
    }  
    else{  
        cout<<"Error in file opening"<<endl;  
    } 
    cout <<"Enter a number: ";
    cin >> chosen_proc;


        }
void display_proc(struct Computer comp, struct Prices price)
{
    for(int i = 0; i < size; i++)
    {
        cout << comp.processor[i] << "  "  << endl
         << "Price: Php"<< price.proc_prices[i] << endl;
         
    }
}

不是您要問的問題,但如果您對代碼進行以下轉換,實際上您會發現這要容易得多。

而不是有兩個 arrays 結構

struct Computer
{
    string processor[size];
    string motherboard[size];
};

struct Prices
{
    double proc_prices[size];
    double mboard_prices[size];
};

Computer computer = ...;
Prices all_prices = ...;

有一個結構數組

struct Computer
{
    string processor;
    string motherboard;
    double proc_price;
    double mboard_price;
};

Computer computers[size] = ...;

這樣,一台計算機的所有信息都保存在一個結構中,而不是分散在多個地方。 你的方法可以工作,但你會發現這種方法更容易處理。

暫無
暫無

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

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