2017-03-05 2406 views
0

我正在使用C++作爲我的程序,而且我非常擅長C++。我已閱讀Get the last element of a std::string,但他們都沒有幫助。我的代碼是:如何獲取C++中字符串的最後一個字符

#include <iostream> 
    #include <string> 

    using namespace std; 

    int main() 
    { 
     string str = "Hello World!"; 
     char endch = str.back(); 
     if (endch == "!") // Here's the error 
     { 
      cout << "Found!" << endl; 
     } else 
     { 
      ; // ; alone does nothing 
     } 
    } 

下面是錯誤

C:\用戶\ ... \桌面\ main.cpp中| 30 |警告:在不確定的行爲字符串字面結果[-Waddress]對比|

C:\用戶\ ... \桌面\ main.cpp中| 30 |錯誤:ISO C++禁止指針和整數[-fpermissive]

我不知道是什麼問題,但之間的比較我猜這是str.back;。如果你知道問題是什麼,請幫忙!

回答

4

因爲您正在比較char和字符串文字。嘗試

if (endch == '!') 

因爲

"!" // <--- is a string literal. 
'!' // <--- it is a character. 
1

你得到一個字符endch。因此,與字符字面值進行比較,而不是字符串字面值。

if (endch == '!') 
3

endch是一個字符。同時"!"是一個char數組。所以==不適用。使用代替"!"

相關問題