본문 바로가기

C++

[C/C++] std::wstring to std::string

 

C++을 다루다보면 wstring string을 다루는 경우가 많습니다. 두 타입을 모두 쓰다보면 변환하는 방법이 필요한데 기존의 웹에서 긁어 찾은 방법 입니다.

wstring path = L"this is path.";
string spath(path.begin(), path.end());

cout << spath << endl;

 

컴파일은 성공합니다만.

std::basic_string<char,std::char_traits<char>,std::allocator<char>>::basic_string'에 대한 첫 번째 참조를 확인하세요.

 

라는 메세지가 출력된다.

 

https://stackoverflow.com/questions/4804298/how-to-convert-wstring-into-string

 

How to convert wstring into string?

The question is how to convert wstring to string? I have next example : #include <string> #include <iostream> int main() { std::wstring ws = L"Hello"; std::string s( ws.begin...

stackoverflow.com

이 글에서 방법은 찾았으나 해더를 찾는 두번의 수고를 덜고자 기록합니다.

 

#include <codecvt> // for wstring_convert
#include <locale>  // for codecvt_utf8
    
wstring path = L"this is path";
wstring_convert<codecvt_utf8<wchar_t>> converter;
string spath = converter.to_bytes(path);
    
cout << spath << endl;

 

 

이상 지저분한 출력을 지워보고자 노력한 작성자입니다.