如何使用不同形式的字符串

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char animal[20]="bear";
const char* bird="wren";
char* ps;
cout<<animal<<" and ";
cout<<bird<<"\n";

cout<<"Enter a kind of animal:";
cin>>animal;

ps=animal;
cout<<ps<<"!\n";
cout<<"Before using strcpy():\n";
cout<<animal<<" at "<<(int *)animal<<endl;
cout<<ps<<" at "<<(int *)ps<<endl;

ps=new char[strlen(animal)+1];
strcpy(ps,animal);
cout<<"After using strcpy():\n";
cout<<animal<<" at "<<(int *)animal<<endl;
cout<<ps<<" at "<<(int *)ps<<endl;
delete [] ps;
system("pause");
return 0;
}

使用new创建一个未命名的结构,演示两种访问结构成员的指针表示法

#include<iostream>
using namespace std;
struct inflatable
{
char name[20];
float volume;
double price;
};
int main()
{
inflatable* ps=new inflatable;
cout<<"Enter name of inflatable item:";
cin.get(ps->name,20);
cout<<"Enter volume in cubic feet:";
cin>>(*ps).volume;
cout<<"Enter price:$";
cin>>ps->price;
cout<<"Name:"<<(*ps).name<<endl;
cout<<"Volume:"<<ps->volume<<" cubic feet\n";
cout<<"Price:$"<<ps->price<<endl;
delete ps;
system("pause");
return 0;
}

使用new和delete来存储通过键盘输入的字符串

#include<iostream>
#include<cstring>
using namespace std;
char* getname(void);
int main()
{
char* name;

name=getname();
cout<<name<<" at "<<(int*)name<<"\n";
delete [] name;

name=getname();
cout<<name<<" at "<<(int*)name<<"\n";
delete [] name;
system("pause");
return 0;
}
char* getname()
{
char temp[80];
cout<<"Enter last name:";
cin>>temp;
char* pn=new char[strlen(temp)+1];
strcpy(pn,temp);

return pn;
}

程序清单4.23

#include<iostream>
using namespace std;
struct antarctica_years_end
{
int year;
};
int main()
{
antarctica_years_end s01,s02,s03;
s01.year=1998;
antarctica_years_end* pa=&s02;
pa->year=1999;
antarctica_years_end trio[3];
trio[0].year=2003;
std::cout<<trio->year<<std::endl;
const antarctica_years_end* arp[3]={&s01,&s02,&s03};
std::cout<<arp[1]->year<<std::endl;
const antarctica_years_end** ppa=arp;
auto ppd=arp;

std::cout<<(*ppa)->year<<std::endl;
std::cout<<(*(ppd+1))->year<<std::endl;
system("pause");
return 0;
}

比较数组、vector对象和array对象

#include<iostream>
#include<vector>
#include<array>
using namespace std;
int main()
{
double a1[4]={1.2,2.4,3.6,4.8};

vector<double> a2(4);

a2[0]=1.0/3.0;
a2[1]=1.0/5.0;
a2[2]=1.0/7.0;
a2[3]=1.0/9.0;

array<double,4> a3={3.14,2.72,1.62,1.41};
array<double,4> a4;
a4=a3;

cout<<"a1[2]:"<<a1[2]<<" at "<<&a1[2]<<endl;
cout<<"a2[2]:"<<a2[2]<<" at "<<&a2[2]<<endl;
cout<<"a3[2]:"<<a3[2]<<" at "<<&a3[2]<<endl;
cout<<"a4[2]:"<<a4[2]<<" at "<<&a4[2]<<endl;

a1[-2]=20.2;
cout<<"a1[-2]:"<<a1[-2]<<" at "<<&a1[-2]<<endl;
cout<<"a3[2]:"<<a3[2]<<" at "<<&a3[2]<<endl;
cout<<"a4[2]:"<<a4[2]<<" at "<<&a4[2]<<endl;
system("pause");
return 0;
}

 posted on 2021-03-10 22:25  HuJiao粉  阅读(62)  评论(0)    收藏  举报