2012-08-30 57 views
8

我已經得到了一個帶有四個單詞行的Listbox。 當我點擊一行時,應該在四個不同的文本框中看到這些單詞。 到目前爲止,我已經得到了一切工作,但我有一個字符轉換的問題。 列表框中的字符串是UnicodeString,但strtok使用char []。 編譯器告知met無法將UnicodeString轉換爲Char []。這是我使用此代碼:將Unicodestring轉換爲字符[]

{ 
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++中學習一些編程。 任何人都可以告訴我如何轉換?

回答

8

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; 
+0

非常感謝您! 我想知道它是如何工作的,但它工作! –

+0

我最近編輯我的帖子,使長度爲ansiB.Length()+ 1的字符數組。這個很重要。確保你做了這個改變,否則你可能會發生隨機崩潰。 –

+0

關閉程序後出現錯誤。當我使用你提供的代碼時,我得到一個acces違規,當我打破它跳轉到Forms.hpp /* TCustomForm.Destroy */inline __fastcall虛擬〜TForm(無效){} 這可能意味着有什麼事情錯誤的東西或東西? –

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;