无法使用变量来比较 c++ 中的字符串
Unable to compare strings in c++ without using variables
当我比较 c++ 中的字符串而不将它们分配给变量时,我没有得到正确的答案。
string a = "286";
string b = "256";
if("286" > "256") cout << "yay";
else cout << "nope";
cout <<endl;
if(a > b) cout << "yay";
else cout << "nope";
输出:
不耶
不使用变量就不能比较字符串吗?为什么?
不使用变量就不能比较字符串吗?
这显然是可能的,但您需要了解您在比较什么。
当你写这个的时候:
"abc" < "cbe"
您比较两个const char *
所以基本上您检查哪个地址较低。要将它们作为字符串进行比较,您需要至少转换其中一个:
std::string( "abc" ) < "cbe"
或更详细:
static_cast<std::string>( "abc" ) < "cbe"
或使用字符串文本:
using namespace std::string_literals;
"abc"s < "cbe"s
然后,您将比较 2 个std::string
对象(就像使用命名变量时一样(。
Slava 的答案涵盖了C++中最正确的方法,它当然是最易读的方法 - 在正常情况下你应该更喜欢它。
另一种解决方案(不涉及std::string
和C编程的典型风格(是使用std::strcmp
:
#include <cstring>
if(std::strcmp("286", "256") == 0)
cout << "yay";
else
cout << "nope";
请注意,这是更不安全的代码(如果要std::strcmp
的任何参数不是指向以 null 结尾的字符数组的指针,则未指定 behaviou(,并且可以说可读性较差。