1.结构体与指针
功能描述:做一个简单的通讯录录入,然后将其保存到文件中。
#include <iostream>
#include<fstream>
#include<string>
using namespace std;
struct yg
{
string name;
string number;
};
int main()
{
yg a;
yg *pa=&a;
cout<<"input the name:";
cin>>pa->name;
cout<<'\n';
cout<<"input the number:";
cin>>pa->number;
cout<<'\n';
cout<<"the name is:"<<a.name<<'\n'<<"the number is:"<<a.number<<'\n';
ofstream test("test.txt");
test<<"the name is:"<<a.name<<'\n';
test<<"the number is:"<<a.number<<'\n';
if(test.is_open())
{
cout<<"file opened succeed";
test.close();
}
else
cout<<"file opened failed";
return 0;
}
2.引用传递
功能描述:实现两个数交换
#include <iostream>
#include<fstream>
#include<string>
using namespace std;
void swap(int &x,int &y);
int main()
{
int x,y;
cout<<"please input two different number:";
cin>>x>>y;
swap(x,y); //这里不需要取址,编译器会自动传地址
cout<<'\n';
cout<<"after swap:"<<x<<' '<<y<<'\n';
return 0;
}
void swap(int &x,int &y) //跟swap(int *x,*y)效果一样,只不过上面调用函数换成swap(&x,&y)
{
int temp;
temp=x;
x=y;
y=temp;
}