C++primer练习12.23-12.26

练习12.23

编写一个程序,连接两个字符串字面常量,将结果保存在一个动态分配的char数组里。重写这个程序,连接两个标准库string对象。

int main()
{
    char a[10]="beautyday";
    char b[5]="yeah";
    
     char *p=new char[15];
     strcpy(p,a);
     strcat(p,b);
    cout<<p<<endl;
    delete []p;
}
int main()
{
    string a="beauty day";
    string b="yeah";
    a+=b;
    cout<<a<<endl;
}
 

练习12.24

编写一个程序,从标准输入读取一个字符串,存入一个动态分配的字符数组中,描述你的程序如何处理边长输入。测试你的程序,输入一个超出你分配的数组长度的字符串

int main()
{
    int n=0;
    cin>>n;
    char *p=new char[n];
    cin>>p;
    cout<<p<<endl;
   delete []p; }

先是输入字符串长度,用来new动态数组,但是输入超长的也能存放并打印出来,不知道为啥

练习12.25

给定下面的new表达式,你应该如何释放pa

::delete【】pa;

练习12.26

用allocator重写第427页程序

int main()
{
    std::allocator <string> alloc;
    int n;
    cin>>n;
    auto p=alloc.allocate(n);
    string s;
    string *q=p;
    while(cin>>s)
    {
        alloc.construct(q++,s);
    }
    for(int i=0;i<n;++i)
    cout<<*(p+i)<<endl;
    while(q!=p)
    alloc.destroy(--q);
    alloc.deallocate(p,n);
    
    cout<<p<<endl;
    
}

 

posted @ 2022-08-09 21:09  yddl  阅读(35)  评论(0编辑  收藏  举报