如何获取C++中字符串的最后一个字符

问题描述:

我正在使用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;。如果你知道问题是什么,请帮忙!

因为您正在比较char和字符串文字。尝试

if (endch == '!') 

因为

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

你得到一个字符endch。因此,与字符字面值进行比较,而不是字符串字面值。

if (endch == '!') 

endch是一个字符。同时"!"是一个char数组。所以==不适用。使用代替"!"