我在我的程序中使用 c++,而且我非常擅长 c++。我已经阅读了获取 std::string 的最后一个元素,但它们都没有帮助。我的代码是:
#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
}
}
Run Code Online (Sandbox Code Playgroud)
以下是错误
C:\Users\...\Desktop\main.cpp|30|警告:与字符串文字比较会导致未指定的行为 [-Waddress]|
C:\Users\...\Desktop\main.cpp|30|错误:ISO C++ 禁止比较指针和整数 [-fpermissive]
我不确定问题是什么,但我猜是str.back;。如果你知道问题是什么,请帮忙!
因为您正在将字符与字符串文字进行比较。尝试
if ( endch == '!' )
Run Code Online (Sandbox Code Playgroud)
因为
"!" // <--- is a string literal.
'!' // <--- it is a character.
Run Code Online (Sandbox Code Playgroud)