2013-05-05 90 views
0

我在以下代碼 中使用set_effect_block將字符串轉換爲固定大小的20字節字符串。將任意字符串轉換爲固定大小的字符串

class editoritems{ 

    public: 

    editoritems(string= ""); 

    void set_effect_block(string paramnamestring)   //set effect block 
    { 
     const char *effectnamevalue=paramnamestring.data(); 
     int length=strlen(effectnamevalue); 
     length=(length<20?length:19); 
     strncpy_s(effe_block,effectnamevalue,length); 
     effe_block[length]='\0'; 
    } 

    string get_effect_block()const{return effe_block;} 

    private: 

    char effe_block[20]; 
}; 

editoritems::editoritems(string h) 
{ 
    set_effect_block(h); 
} 

這是一個很好的方法嗎? 有沒有更快的方法?

+0

那麼你當然不需要'strlen'來獲得'std :: string'的長度。 – 2013-05-05 08:05:55

回答

3

試試這個:

void set_effect_block(string paramnamestring) 
{ 
    size_t copied = paramnamestring.copy(effe_block, 19); 
    effe_block[copied] = '\0'; 
} 

BTW:你可能要考慮使用const std::string& paramnamestring作爲參數editoritems::set_effect_block(),使串不需要被複制到被傳遞給函數。

+0

好,非常感謝,我會試一試。 – Sonicpath 2013-05-05 12:26:56