c++动态结构数组、文件输入输出、分支语句和循环语句
#include<iostream> #include<fstream> #include<cstdlib> using namespace std;//命名空间要放在结构体定义之前 const int size=50; struct jxz//定义结构体 { char name[size]; double price; }; int main() { cout<<"enter the name of file:"; char filename[size]; cin.getline(filename,size);//输入指定文件名 ,要从绝对路径获取文件名,比如D:\aaa.txt ifstream inFile; inFile.open(filename);//inFile与文件相关联 ofstream outFile;//定义文件输出对象 outFile.open("str.txt");//outFile与文件相关联 ,输出也可以写其他路径名,比如D:\str.txt if(!inFile.is_open())//检查是否可以打开文件 { cout<<"can not open the file:"<<filename<<endl; exit(EXIT_FAILURE); } int number,i; inFile>>number;//文件读取 inFile.get(); jxz *p=new jxz [number];//定义动态结构数组,本质上是动态数组,只是每个数组元素类型都是结构体 for (i=0;i<number;++i) { inFile.getline(p[i].name,size);//类似于cin的输入方式 ,动态结构数组用句点操作符 inFile>>p[i].price;//如果只是动态结构的话,用指针表示的时候那么就用箭头操作符 inFile.get();//去掉换行符 } int a=0; for (i=0;i<number;++i)//for循环处理结构数组 { if(p[i].price>=10000)//分支语句判断 { if(a==0)//定义标志位,便于分类 { outFile<<"grand patrons:"<<endl; a++; } outFile<<p[i].name<<endl; outFile<<p[i].price<<endl; } } for (a=0,i=0;i<number;++i) { if(p[i].price<=10000) { if(a==0) { outFile<<"patrons:"<<endl; a++; } outFile<<p[i].name<<endl; outFile<<p[i].price<<endl; } } delete [] p;//释放指针 inFile.close();//关闭文件 return 0; }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。