转换的UnicodeString为Char []

问题描述 投票:8回答:2

我有一个从一个列表框至极包含四个字线。当我在一行中单击,这些话应在四个不同的文本框可以看出。到目前为止,我已经得到了一切工作,但我有个字符转换的问题。从列表框中的字符串是一个的UnicodeString但strtok的使用一个char []。编译器告诉遇见不能转换的UnicodeString到char []。这是我使用此代码:

{
 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;
    }
}

我知道我的代码does not看起来不错,很糟糕实际。我只是在学习C ++的一些编程。谁能告诉我如何转换呢?

c++builder chars
2个回答
8
投票

strtok的实际修改你的字符数组,所以你需要建立你被允许修改字符数组。直接引用到的UnicodeString串将无法正常工作。

// 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;  

0
投票

这对我的作品,并为我节省了转换成AndiString

// Using a static buffer
#define MAX_SIZE 256
UnicodeString ustring = "Convert me";
char mbstring[MAX_SIZE];

    wcstombs(mbstring,ustring.c_str(),MAX_SIZE);

// Using dynamic buffer
char *dmbstring;

    dmbstring = new char[ustring.Length() + 1];
    wcstombs(dmbstring,ustring.c_str(),ustring.Length() + 1);
    // use dmbstring
    delete dmbstring;
© www.soinside.com 2019 - 2024. All rights reserved.