2013-07-03 1 views
1

세 가지 프로그램이 있습니다. programA의 코드는 다음과 같다 :C++에서 std :: hex 및 std :: wios :: hex를 사용할 때 출력에 대한 이유를 설명 할 수 있습니까?

A0 A1을 A2에서 A3

programB의 코드는 다음과 같다 :

여기
#include "stdafx.h" 
#include <iostream> 
#include <sstream> 
#include <locale> 
using namespace std; 
int _tmain(void) 
{ 
    wstringstream s2;  
    TCHAR waTemp2[4] = {0xA0, 0xA1, 0x00A2, 0xA3}; 
    for (int i = 0; i < 4; i++) 
    { 
    s2<< hex << waTemp2[i] << " "; 
    } 
    wstring strData2 = s2.str(); 
    wcout << strData2.c_str() <<endl; 
    return 0; 
} 

은 여기

#include "stdafx.h" 
#include <iostream> 
#include <sstream> 
#include <locale> 
using namespace std; 
int _tmain(void) 
{ 
    wstringstream s2;  
    TCHAR waTemp2[4] = {0xA0, 0xA1, 0x00A2, 0xA3}; 
    for (int i = 0; i < 4; i++) 
    { 
    s2<< hex <<(unsigned int)waTemp2[i] << " "; 
    } 
    wstring strData2 = s2.str(); 
    wcout << strData2.c_str() <<endl; 
    return 0; 
} 

가 출력되고 출력 :

????

programC의 코드는 다음과 같습니다 :

2,048,160 2,048,161 2,048,162 2,048,163

당신이 나에게 이유 표준의 차이 :: wios 말할 수 : 여기

#include "stdafx.h" 
#include <iostream> 
#include <sstream> 
#include <locale> 

using namespace std; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    wstringstream s2;  
    TCHAR waTemp2[4] = {0xA0, 0xA1, 0x00A2, 0xA3}; 
    for (int i = 0; i < 4; i++) 
    { 
    s2 << std::wios::hex <<(unsigned int)waTemp2[i] << " "; 
    } 
    wstring strData2 = s2.str(); 
    wcout<< strData2.c_str() <<endl; 
    return 0; 
} 

는 출력 :: hex 및 std :: hex, std :: hex < < waTemp2 [i] 및 std :: hex < < (부호없는 int) waTemp2 [i] 결과가 다릅니다.

대단히 감사합니다!

답변

1

std::hex은 조작자입니다. 정수를 전달할 때 스트림이 16 진수로 출력되도록 설정합니다. 스트림에서 setf(std::wios::hex, std::wios::basefield);을 호출하는 것과 같습니다 (넓은 스트림을 가정 할 때). 예를 들어, 다음 코드 수정을 시도하십시오. 동일한 결과가 나타납니다.

wchar_t waTemp2[4] = {0xA0, 0xA1, 0x00A2, 0xA3}; 
s2.setf(std::wios::hex, std::wios::basefield); 
for (int i = 0; i < 4; i++) 
{ 
    s2 << (unsigned)waTemp2[i] << " "; 
} 

std::wios::hex은 비트 마스크 플래그로 사용되는 정수입니다. 스트림을 설정하는 조작자와 혼동하지 마십시오. coliru 예를 들어 다음은 8입니다.

std::cout << std::wios::hex; 

스트림의 형식 플래그를 업데이트하기 위해 비트 마스크로 사용됩니다.

enum fmtflags 
{ 
    _hex = 1L << 3, 
}; 

class ios_base 
{ 
    static const fmtflags hex = _hex; 
}; 

당신이 2048160 2048161 2048162 2048163을보고있는 이유는 그냥 std::wios::hex(unsigned int)waTemp2[i]의 번호를 인쇄되어 있습니다 : 그것은 (here하면 libstdC++의 실제 정의 참조) 다음과 같이 정의됩니다. 사이에 공백 추가 s2 << std::wios::hex << " " << (unsigned int)waTemp2[i] << " ";

s2 << hex << waTemp2[i] << " ";의 문제는 std::hex은 정수에만 사용됩니다. wchar_t은 정수가 아니므로 해당 문자를 인쇄합니다.

+0

대단히 감사합니다. 아직 두 가지 질문이 있습니다. – yaoike

+0

@yaoike : 두 가지 질문은 무엇입니까? –

+0

대단히 감사합니다. 아직 세 가지 질문이 있습니다. 1. std :: hex가 조작자라고했습니다. 정수를 전달할 때 스트림이 16 진수로 출력되도록 설정합니다. TCHAR 대신 정수를 전달하면 왜 작동합니까? std :: hex manipulator는 C++ 참조에서 정수를 취할 수 없습니다. [link] (http://www.cplusplus.com/reference/ios/hex/? kw = 16 진수). 2.''ios_base & hex (ios_base & str); '형태 : – yaoike