Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Unicodestring to Char[]

I've got a form with a Listbox which contains lines of four words. When I click on one line, these words should be seen in four different textboxes. So far, I've got everything working, yet I have a problem with chars converting.

The string from the listbox is a UnicodeString but the strtok uses a char[]. The compiler tells me it "Cannot Convert UnicodeString to Char[]". This is the code I am using for this:

{
 int a;
 UnicodeString b;

 char * pch;
 int c;

 a=DatabaseList->ItemIndex;   //databaselist is the listbox
 b=DatabaseList->Items->Strings[a]; 

 char str[] = b; //This is the part that fails, telling its unicode and not char[].
 pch = strtok (str," ");      
 c=1;                          
 while (pch!=NULL)
    {
       if (c==1)
       {
          ServerAddress->Text=pch;
       } else if (c==2)
       {
          DatabaseName->Text=pch;
       } else if (c==3)
       {
          Username->Text=pch;
       } else if (c==4)
       {
          Password->Text=pch;
       }
       pch = strtok (NULL, " ");
       c=c+1;
    }
}

I know my code doesn't look nice, pretty bad actually. I'm just learning some programming in C++.

How can I convert this?

like image 282
Stefan Oostwegel Avatar asked Aug 30 '12 14:08

Stefan Oostwegel


Video Answer


1 Answers

strtok actually modifies your char array, so you will need to construct an array of characters you are allowed to modify. Referencing directly into the UnicodeString string will not work.

// first convert to AnsiString instead of Unicode.
AnsiString ansiB(b);  

// allocate enough memory for your char array (and the null terminator)
char* str = new char[ansiB.Length()+1];  

// copy the contents of the AnsiString into your char array 
strcpy(str, ansiB.c_str());  

// the rest of your code goes here

// remember to delete your char array when done
delete[] str;  
like image 77
Jeff Wilhite Avatar answered Sep 27 '22 23:09

Jeff Wilhite