1. 程式人生 > >C++ 中使用字元陣列來存放未知長度的字串

C++ 中使用字元陣列來存放未知長度的字串

#include<iostream>

#include<string>

using namespace std;

int main()
{
   size_t arry_size = 10;
   char * p_str = new char[arry_size];
   int count =0;
   char temp;


   while(cin.get(temp))
   {
       count ++;
       if(count+1 > arry_size)
       {
           char *p_temp = new char[++arry_size];
           strcpy(p_temp,p_str);
           delete [] p_str;
           p_str = p_temp;
       }


       p_str[count-1] = temp;
   }
   p_str[count]= '\0';


   for(size_t i =0 ;i <arry_size ; ++i)
   {
       cout<< p_str[i];
   }


   cout<<endl;
   cout<<p_str<<endl;
}

=======================================================================

核心思路就是在空間不夠時,自己模擬一個realloc 的過程。

比較已輸入字元數和已開闢陣列大小, 若大小不夠, 則開闢一個更大的陣列,將老的資料拷貝到新的陣列,釋放老的陣列, 同時將老的指標指向新的陣列。

上面有一點主意的是輸入格式:  cin.get(temp)  , 這中輸入格式會保留空格

若直接使用cin>>temp , 則會過濾掉空格

PS.  C++ 中還是儘量使用string , 簡單方便,   當然花樣作死不算