2010-12-23 128 views
4
#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的值, 我該如何糾正這種情況?C++字符串比較

+1

你是從舊的課本中得到這個嗎? – silent 2010-12-23 05:24:35

回答

1

將-70的二進制等效值看作1個字符。

2

字符串總是比較,無論unsigned char實際字符的signess的。

std::string了由C此行爲,其中的strcmp使用的範圍在0-255字符即使char在-128 - 127

所以基本上是-70 186和186> 'A'

編輯:參考標準。我沒有C++二千零三分之九十八靠近我剛剛的C++ 0x,但是:

「工作草案,標準C++編程語言」,N2915,21.2.3.1,此言5說:

對於unsigned char類型,雙參數成員eq和lt的定義應與內置運算符==和<相同。

即字符相比,無符號字符。 (它引用到性格特質專業化對於char)

+0

我似乎無法在標準中找到這個要求。 – 2010-12-23 05:48:20

3

在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'的定義與內置運算符<相同。

的N3126草案,21.2.3.1:5規定應當作爲無符號的字符。