无法在没有使用变量的情况下比较C++中的字符串 当我比较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";
输出: 没有 耶 不使用变量就无法比较字符串吗?为什么? 不使用变量就无法比较字符串吗 这显然是可能的,但你需要理解你在比较什么 当你写这篇文章时:无法在没有使用变量的情况下比较C++中的字符串 当我比较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";,c++,string,C++,String,输出: 没有 耶 不使用变量就无法比较字符串吗?为什么? 不使用变量就无法比较字符串吗 这显然是可能的,但你需要理解你在比较什么 当你写这篇文章时: "abc" < "cbe" 或者更详细: static_cast<std::string>( "abc" ) < "cbe" 或使用字符串文字: using namespace std::string_literals; "abc"s < "cbe"s 你将比较2个STD::String对象,就像你使用命名变量
"abc" < "cbe"
或者更详细:
static_cast<std::string>( "abc" ) < "cbe"
或使用字符串文字:
using namespace std::string_literals;
"abc"s < "cbe"s
<>你将比较2个STD::String对象,就像你使用命名变量时所做的那样。 < Pr> SLVA的答案涵盖了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";
另一种不涉及std::string的解决方案和C编程的典型风格是:
请注意,这是更不安全的代码行为。如果std::strcmp的任何参数不是指向以null结尾的字符数组的指针,并且可读性较差,则未指定此行为。字符串文字是字符数组const char[N],而不是字符串。if286>256会比较两个const char*指针,而不是std::strings。您可以改变您的条件,以明确:虽然:IFSTD::String 86> STD::String 256 CUT现代C++有能力做的是一个字符串文字的S后缀,就像是一个被问得很好的问题,为什么它被否决了?
#include <cstring>
if(std::strcmp("286", "256") == 0)
cout << "yay";
else
cout << "nope";