微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 fstream C++

如何解决使用 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;
         
    }
}

解决方法

不是您要问的是什么,但如果您对代码进行以下转换,实际上您会发现这更容易。

而不是有两个数组结构

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] = ...;

通过这种方式,一种计算机的所有信息都集中在一个结构中,而不是分散在多个地方。你的方法可行,但你会发现这种方法更容易处理。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。