C++ 使用fstream C++;
我被困在代码中,我已经初始化了struct成员,但我不知道如何在txt文件中编辑或删除它。(这可能吗?)因为我正在做一个关于处理器和主板的“pc零件店”。任何提示都非常感谢。也很抱歉,如果我的代码不干净,我是初学者C++ 使用fstream C++;,c++,c++11,C++,C++11,我被困在代码中,我已经初始化了struct成员,但我不知道如何在txt文件中编辑或删除它。(这可能吗?)因为我正在做一个关于处理器和主板的“pc零件店”。任何提示都非常感谢。也很抱歉,如果我的代码不干净,我是初学者 #include<iostream> #include<string> #include<fstream> const int size = 5; struct Computer
#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;
}
}
#包括
#包括
#包括
常数int size=5;
结构计算机
{
字符串处理器[大小];
字符串主板[大小];
};
结构价格
{
双加工价格[尺寸];
双mboard_价格[尺寸];
};
无效显示程序(结构计算机组件、结构价格);
int main(){
int选择的进程,选择的飞蛾;
计算机={
{“1.带LED照明的华硕Prime A320M-K AMD AM4 uATX主板,DDR4 3200MHz,32Gb/s M.2,HDMI,SATA 6Gb/s,USB 3.0”,“2.MSI H410M-A PRO LGA 1200支持第10代Intel Core和奔腾Gold/Celeron处理器”},//处理器或阵列初始化
{“1.英特尔奔腾双核G2030 3.0Ghz 3MB缓存LGA1155 22nm处理器”,“2.英特尔酷睿i3-7100处理器(3M缓存,3.90GHz)”}//主板阵列初始化
};
价格所有价格={
{2499, 5999},
{2999, 3999}
};
系统(“颜色0A”);//这只是一个设计,我正在测试它
流proc1(“processor.txt”,ios::app);
OfStreamMother1(“motherboard.txt”,ios::app);
cout这不是您要问的问题,但是如果您对代码进行以下转换,您会发现这要容易得多
而不是有两个数组结构
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] = ...;
这样,一种型号计算机的所有信息都集中在一个结构中,而不是分散在多个位置。您的方法可以工作,但您会发现这种方法更易于处理。不可能从文件中删除文本。也不可能编辑文件中的文本,除非新文本的长度完全相同h作为旧文本。你想要做的方法是将整个文件读入内存,在内存中进行编辑(这很容易)然后把所有的数据都写回文件中,忘记编辑一部分文件,在整个文件上运行。注意C++可以从C中学习到一些东西。其中一个是,当声明一个类型的变量时,总是需要编写<代码>结构>代码>。编译器知道什么是< Co > > >计算机
是(除非你笨到可以重新定义它),所以你只需写计算机comp
就可以了。还可以查看参考资料。非常方便。