c++动态结构数组、文件输入输出、分支语句和循环语句
  PjuqN0S4qpGM 2023年11月02日 88 0


#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;
}




【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
PjuqN0S4qpGM