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