C++primer 12.2.1節練習

來源:互聯網
上載者:User

標籤: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節練習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.