2016-10-13 6 views
-1

std::string을 ASCII 16 진수 출력으로 변환하는 코드가 있습니다. 코드는 정상적으로 실행되지만 작은 문제가 하나 있습니다. 공간을 16 진수로 변환하지 않습니다. 어떻게하면 그 문제를 해결할 수 있을까요?문자열을 ASCII로 변환 C++

#include <iostream> 
#include <string> 
#include <sstream> 


int main(){ 

    std::string text = "This is some text 123...";` 

    std::istringstream sin(text); 
    std::ostringstream sout; 
    char temp; 
    while(sin>>temp){ 
     sout<<"x"<<std::hex<<(int)temp; 
    } 
    std::string output = sout.str(); 
    std::cout<<output<<std::endl; 
    return 0; 
} 
+5

'연산자 >>'는 공백을 건너 뜁니다. '연산자 >>'를 사용하지 마십시오. –

+0

['std :: noskipws'] (http://en.cppreference.com/w/cpp/io/manip/skipws) –

답변

2

는 입력 스트림을 생성 사용 반복자한다.

2

operator >> 개의 스트림은 기본적으로 공백을 건너 뜁니다. 즉, 문자열에서 공백을 치면 건너 뛰고 다음 비 공백 문자로 이동합니다. 다행히 여기에 stringstream을 사용할 이유가 없습니다. 이것은 int 다음 출력이 초과 cout로 문자열의 모든 문자를 변환합니다 단지 일반 ranged based for loop

int main() 
{ 
    std::string text = "This is some text 123...";` 

    for (auto ch : test) 
     cout << "x" << std::hex << static_cast<int>(ch); 

    return 0; 
} 

처럼 우리가 사용할 수 있습니다. 특히, 스트림 추출기 ( operator>>)가 공백 이동 사실을

template <class Iter> 
void show_as_hex(Iter first, Iter last) { 
    while (first != last) { 
     std::cout << 'x' << std::hex << static_cast<int>(*first) << ' '; 
     ++first; 
    } 
    std::cout << '\n'; 
} 

int main() { 
    std::string text = "This is some text 123..."; 
    show_ask_hex(text.begin(), text.end()); 
    return 0; 
} 

이것은 스트림 입력의 복잡성을 회피하고, 대신 모든기구