gpt4 book ai didi

C++ 字符串比较

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:40:15 27 4
gpt4 key购买 nike

#include "stdafx.h"
#include "iostream"
#include "string"

using namespace std;

void main()
{
string a = "a";
string b(1, -70); /*constructor, create a string having 1 character that its value is equal to -70*/
cout<<((b>a)?b:a);
}

//output on screen: b was printed, not a (!)

为什么b>a虽然b的值小于a的值?我该如何纠正这种情况?

最佳答案

在 VS2010 上,我发现该字符已签名 - 因此不是所需的解释。通过比较调试器,我最终找到了代码:

template<> struct char_traits<char>
{ // properties of a string or stream char element
typedef char _Elem;
typedef _Elem char_type;
typedef int int_type;
typedef streampos pos_type;
typedef streamoff off_type;
typedef _Mbstatet state_type;

static int __CLRCALL_OR_CDECL compare(const _Elem *_First1, const _Elem *_First2,
size_t _Count)
{ // compare [_First1, _First1 + _Count) with [_First2, ...)
return (_CSTD memcmp(_First1, _First2, _Count));
}
// etc
};

所以真正的比较归结为 memcmp .检查一下,我们发现“评估为无符号字符值”,因此出现了问题。

比照。 Arytom 的回答 - 有趣的是,我不知道这一点。查找它:

关于 char_traits 的 1998 标准 21.1.3.1:6 声明“lt”与内置运算符 < 的定义相同。

N3126 草案 21.2.3.1:5 声明它应该与 unsigned char 一样。

关于C++ 字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4516078/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com