2014-03-27 42 views
2

在寫入我的代碼期間遇到問題。我使用一個函數作爲參數對象,類型是LPCSTR。對象聲明如下所示: LPCTSTR lpFileName; 首先,我用定義的變量,這是futher分配給lpFileName的對象是這樣的:將字符串轉換爲LPCTSTR

#define COM_NR L"COM3" 
lpFileName = COM_NR 

使用這種方式,可以容易地通過lpFileName的對象參數的功能。無論如何,我不得不改變定義我的端口號的方式。目前,我從* .txt文件中讀取文本並將其保存爲字符串變量,例如「COM3」或「COM10」。主要問題是將字符串正確轉換爲LPCSTR。我找到了很好的解決方案,但最終似乎沒有正常工作。我的代碼如下所示:

string temp; 
\\code that fill temp\\ 
wstring ws; 
ws.assign(temp.begin(),temp.end()); 

我認爲轉換都是正確的話,也許它沒有因爲當我打印一些東西它使我想知道爲什麼它,因爲我想不工作,我不明白這一點: COUT temp_cstr():COM3 COUT LCOM3:0x40e586 COUT ws.c_str():0x8b49b2c

爲什麼LCOM3和ws.c_str()不包含相同?當我將lpFileName = ws.c_str()傳遞給我的函數時,它的工作原理是不正確的。另一方面,傳遞lpFileName = L「COM3」會成功。使用CPP 我的代碼,而IDE是QtCreator

回答

1

最終,我與陷阱使用轉換功能s2ws管理()和做一些操作。我把我的精神放在那裏,對於那些在轉換字符串時會遇到類似麻煩的人來說。在我的第一篇文章中,我寫道,我需要將字符串轉換爲LPCTSTR,並最終發現我的函數中的參數不是,LPCTSTR,而是常量wchar_t *的LPCWSTR。 所以,soulution:

string = "COM3"; 
wstring stemp; 
LPCWSTR result_port; 
stemp = s2ws(port_nr); 
result_port = stemp.c_str(); // now passing result_port to my function i am getting success 

聲明s2ws的:

wstring s2ws(const std::string& s) 
{ 
    int len; 
    int slength = (int)s.length() + 1; 
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
    wchar_t* buf = new wchar_t[len]; 
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); 
    std::wstring r(buf); 
    delete[] buf; 
    return r; 
} 
0

嘗試使用wostringstream

string temp; 
\\code that fill temp\\ 
wostringstream ost; 
ost << temp.c_str(); 
wstring ws = ost.str(); 
+0

我不能指定WS wstring的變量LPCTSTR,我得到:錯誤C2440: '類型轉換':無法從 '的std :: wstring的' 轉換爲 'LPCTSTR' – user2263166

+0

嘗試使用'ws.c_str ()'將wstring強制轉換爲LPCTSTR。 – Pegieo

0

我有這個掙扎了好一陣子。經過相當多的挖掘後,我發現這是最好的;你可以試試這個。

std::string t = "xyz"; 
CA2T wt (t.c_str());