我有一个包含四个单词行的列表框的表单。
当我单击一行时,应该会在四个不同的文本框中看到这些词。
到目前为止,我已经一切正常,但我在字符转换方面遇到了问题。
列表框中的字符串是 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;
}
}
我知道我的代码看起来不太好,实际上很糟糕。我只是在学习一些 C++ 编程。我该如何转换?
最佳答案
strtok 实际上会修改您的 char 数组,因此您需要构造一个允许修改的字符数组。直接引用到 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;
关于char - 将 Unicodestring 转换为 Char[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12199796/