2013-03-05 148 views
0

我想投一個char來使用此功能的字符串:(字符串)字符類型轉換

int charIndexDistance (char a, char b) 
{ 
    if (indexical) { 
     string test_a = convertOntology((string)a, 0); 
     string test_b = convertOntology((string)b, 0); 
     cout << test_a << " " << test_b << endl; 

     int test = abs(char_index[a] - char_index[b]); 
     return test; //measure indexical distance between chars 
    } else 
     return 1; 
} 

,但我得到這個「錯誤C2440:‘類型轉換’:無法從‘字符’轉換爲「STD :: string「

什麼是thr問題?以及如何將字符串轉換爲字符串 - 我應該使用字符串附加?

也行,coutint test是用於調試目的和將在後面

回答

3

除去目前根本沒有這樣的轉換。相反,您必須手動構建一個字符串:

string(1, a) 

這使用constructor taking a length and a char to fill the string with

在你的代碼的情況下:

string test_a = convertOntology(string(1, a), 0); 
string test_b = convertOntology(string(1, b), 0); 

即使一個合適的構造函數/施放存在你的代碼會很糟糕,因爲you should avoid C-style casts in C++。這種情況需要改爲static_cast

+0

謝謝你 - 感謝你的專業知識 – 2013-03-05 21:23:52

2

A char不是字符串。

A char也不是空終止的字符串。

以空字符結尾的字符串是一個char數組,末尾爲空字符。

+0

所以我可以做點像'char a;字符串a_test ='a'+'\ n'' – 2013-03-06 00:55:30

+1

@forest不,因爲添加兩個'char'不會連接它們,它會添加它們的字節值。但是你可以連接一個(空)字符串和一個'char':'string()+'a''工作(但可能比我的代碼效率低)。請注意''「」+'a'' does not * work,因爲'「」'不是*字符串,而是以空字符結尾的'char'數組。 – 2013-03-06 09:47:46

0

string(1,a)

0

一切都已經提到過的作品更換(string)a,但你也可以試試:

焦炭mychar = 'A';

string single_char =「」;

string + = mychar;

希望有幫助!