码迷,mamicode.com
首页 > 编程语言 > 详细

C++primer 12.2.1节练习

时间:2017-08-29 20:34:49      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:turn   clu   world   new   char   str   c++   use   delete   

练习12.23

字符串常量

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     char a[] = "hello";
 9     char b[] = "world";
10     char * pa = new char[10];
11     pa = a;
12     for (auto i = 0; i != 5; ++i)
13         cout << pa[i];
14     cout << endl;
15     for (auto i = 0,j = 5; i != 5; ++i, ++j)
16     {
17         pa[j] = b[i];
18     }
19     for (auto i = 0; i != 10; ++i)
20         cout << pa[i];
21     cout << endl;
22     system("pause");
23     return 0;
24 }

string对象

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     string str1;
 9     string str2;
10     while (cin >> str1 >> str2)
11     {
12         string * str = new string[50];
13         *str = str1 + str2;
14         cout << *str << endl;
15         delete[] str;
16     }
17     system("pause");
18     return 0;
19 }

 

练习12.24

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     string str1;
 9     while (cin >> str1)
10     {
11         char * str = new char[str1.size()];
12         for (auto i = 0; i != str1.size(); ++i)
13             str[i] = str1[i];
14         for (auto i = 0; i != str1.size(); ++i)
15             cout << str[i];
16         cout << endl;
17         delete[] str;
18     }
19     system("pause");
20     return 0;
21 }

可以使用输入的字符串的长度来动态的分配字符长度;

练习12.25

1 delete[] pa;

 

C++primer 12.2.1节练习

标签:turn   clu   world   new   char   str   c++   use   delete   

原文地址:http://www.cnblogs.com/wuyinfenghappy/p/7449905.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!