how to add null at the end of wstring?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bajajv
    New Member
    • Jun 2007
    • 152

    how to add null at the end of wstring?

    Hi,
    I want to implement the cstring class using wstring. but in assignement operator, I need to know how to add null while assigning some wchar_t type of data to the wstring. below is my code -

    Code:
    class CString 
    { 
    public:
    	wstring wStr; 
    	CString () {wStr = L"";} 
    	CString (wstring str) {wStr = str;} 
    	CString& operator =( const CString& stringSrc );
    	CString& operator =( wchar_t wcChar );
    };
    int main()
    {
    	CString name = L"Vipul Bajaj";
    	CString name1 = L"Santosh Patil";
    
    	name1 = name;
    	wchar_t aaa = L'Z';
    	name1 = aaa;
    
    	return 0; 
    }
    
    CString& CString::operator =( const CString& stringSrc )
    {
    	this->wStr.assign(stringSrc.wStr);
    	return *this;
    }
    
    CString& CString::operator =( wchar_t wcChar )
    {
    	this->wStr.assign(&wcChar);
    	int iLen = ((int) (sizeof (wcChar))) + 1;  //Will this calculate the       exact                                              size required for both unix and windows
    	this->wStr[iLen] = 0;  
    	return *this;
    }
    The second assignment operator is adding null after some garbage value copied into the wstring.

    Also, see the code below-
    Code:
    int iLen = ((int) (sizeof (wcChar))) + 1;
    Will this calculate the exact size required for both unix and windows?

    Thanks,
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Why are you dong this? wstring already implements everything. Your Cstring is a duplication.

    Your assignment operator is:

    Code:
    CString& CString::operator =( wchar_t wcChar )
    {
    this->wStr = wcChar;
    
    return *this;
    }
    You don't need a length variable. The length is always wStr.size().

    Comment

    • bajajv
      New Member
      • Jun 2007
      • 152

      #3
      Yes. But when I check in watch window of VS2005, for this code -
      name1 = "ABC";
      wchar_t aaa = L'Z';
      name1 = aaa;
      I see name1 as "Z****" - 4 squares after Z.
      And when I add null, it shows 3 junk squares.
      Thats why, I was in doubt whether it is correct or not?

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Everything looks fine in the Watch window of Visual Studio.NET 2008.

        Comment

        Working...