2010-10-18 105 views
2

我有這個變量dirpath2哪裏存放的路徑最深的目錄名稱:C++ tstring比較

typedef std::basic_string<TCHAR> tstring; 
tstring dirPath = destPath; 
tstring dirpath2 = dirPath.substr(destPathLenght - 7,destPathLenght - 1); 

我希望能夠比較一下它另一個字符串,是這樣的:

if (_tcscmp(dirpath2,failed) == 0) 
{ 
...  
} 

我已經嘗試了很多東西,但似乎沒有任何工作。任何人都可以告訴我該怎麼做,或者我做錯了什麼?

請記住,我對C++幾乎一無所知,而這整件事情讓我瘋狂。提前

+1

想要比較2 std :: string嗎?爲什麼不直接使用==? – 2010-10-18 14:04:24

回答

7

std::basic_string<T>

感謝名單已經超載operator==,試試這個:

if (dirpath2 == failed) 
{ 
... 
} 

或者你可以做到這樣。由於std::basic_string<T>沒有的隱式轉換操作符const T*,您需要使用c_str成員函數將轉換爲const T*

if (_tcscmp(dirpath2.c_str(), failed.c_str()) == 0) 
{ 
... 
} 
+0

這個人做了詭計,從而使我不再瘋狂。非常感謝! – hikizume 2010-10-18 14:32:19

4

你爲什麼要使用_tcscmp用C++字符串?只要使用它內置的平等操作:

if(dirpath2==failed) 
{ 
    // ... 
} 

看一看提供comparison operatorsmethods可以與STL字符串中使用。

通常,如果使用C++字符串,則不需要使用C字符串函數;但是,如果需要將C++字符串傳遞給需要C字符串的函數,則可以使用c_str()方法獲取帶有指定C++字符串實例內容的const C字符串。

順便說一句,如果你知道「幾乎旁邊沒有關於C++」,你應該真的得到一個C++的書,讀它,即使你來自C.

0

的std :: basic_string的有==運算符。使用字符串類模板:

if (dirpath2 == failed) 
{ 
... 
}