wstring wstr(L"ㄱ") 을 string 으로 변환..

paek1ju의 이미지

안녕하세요.

wstring 을 이용해서 한글 다루는 문제로 고생하고 있습니다..

목적은
wstring wstr(L"ㄱ") 을 string str 으로 변경해서 사용하는 겁니다.
여러가지 예제를 해보다가 다 안되어 그나마 근접한 변환 함수로 해보고 있습니다.

아래가 연습 소스인데요.
string str ("ㄱ"); 을 다루는 결과가 제가 원하는 결과 입니다.

str size 3
ㄱ
227
132
177

헌데,
wstring wstr(L"ㄱ") 을 string str으로 변환하기 위해
wcs_to_mbs() 코드를 이용하면 아래 결과 같이 can't convert wstring to string 에러가 납니다.

wstring wstr(L"ㄱ") 대신 wstring wstr(L"a") 로 하면 변환이 잘되네요.
혹시 뭐 잘못해서 wstring wstr(L"ㄱ") 이 변환이 안되는 것일 까요..

#include <string>
#include <iostream>
#include <vector> 
#include <stdexcept>
 
 
using namespace std;
 
 
int string_korean_practice()
{
	int i = 0;
 
	/****************************************************************************************/
	const unsigned char *ctemp;
	string str ("ㄱ");
 
	printf("str size %d\n", (int)str.size());	
 
	// string을 char로 변환
	ctemp = (const unsigned char *)str.c_str();
 
	for (i = 0; i < str.size(); i++) {
		printf("%c", ctemp[i]);  // "ㄱ" 출력
	}
	printf("\n");
 
	for (i = 0; i < str.size(); i++) {
		printf("%d\n", ctemp[i]);  // "ㄱ" 을 int로 출력
	}
	/****************************************************************************************/
 
	return 0;
}
 
string wcs_to_mbs(wstring const& str, locale const& loc = locale())
{
    typedef codecvt<wchar_t, char, mbstate_t> codecvt_t;
    codecvt_t const& codecvt = use_facet<codecvt_t>(loc);
    mbstate_t state = mbstate_t();
    vector<char> buf((str.size() + 1) * codecvt.max_length());
    wchar_t const* in_next = str.c_str();
    char* out_next = &buf[0];
    codecvt_base::result r = codecvt.out(state, 
		str.c_str(), str.c_str() + str.size(), in_next, 
		&buf[0], &buf[0] + buf.size(), out_next);
    if (r == codecvt_base::error)
		throw runtime_error("can't convert wstring to string");   
    return string(&buf[0]);
}
 
int wstring_korean_practice()
{
	int i = 0;
 
	/****************************************************************************************/
	const unsigned char *ctemp;
	wstring wstr (L"ㄱ");
	string str;
 
	// wstring을 string으로 변환
	// str = wstr2str(wstr);  ???
	str = wcs_to_mbs(wstr);
 
	printf("str size %d\n", (int)str.size());	
 
	// string을 char로 변환
	ctemp = (const unsigned char *)str.c_str();
 
	for (i = 0; i < str.size(); i++) {
		printf("%c", ctemp[i]);  // "ㄱ" 출력
	}
	printf("\n");
 
	for (i = 0; i < str.size(); i++) {
		printf("%d\n", ctemp[i]);  // "ㄱ" 을 int로 출력
	}
	/****************************************************************************************/
 
	return 0;
}
 
int main (int argc, char * const argv[]) {
 
	string_korean_practice();
	wstring_korean_practice();
 
    return 0;
}
 
** 결과
 
str size 3
ㄱ
227
132
177
terminate called after throwing an instance of 'std::runtime_error'
  what():  can't convert wstring to string
Abort trap

jachin의 이미지

string은 한 문자마다 8 bit 이고,
wstring은 한 문자마다 16 bit 인데,
한글은 8 bit로 나타내지 못하고 16 bit 을 모두 쓰게 끔 되어 있는 것으로 알고 있습니다.
알파벳은 8 bit 체계 내에서도 해당 문자가 있기 때문에 변환가능하지 않겠습니까?

익명 사용자의 이미지

utf-8을 이용하던지..

euc-kr 로

bacon의 이미지

현재 시스템 locale이 한글을 지원하다고 하면, wcs_to_mbs의 두번째 인자의 기본값을 locale("")로 바꾸면 될겁니다. 아니면 원하는 한글 locale을 직접넣어 주던가요... locale생성할때 아무 인자도 안주면 아마 classic locale로 잡히는 것으로 기억합니다.

익명 사용자의 이미지

string wcs_to_mbs(wstring wstr)
{
const wchar_t *str = wstr.c_str();
char mbs[100] = {0};
mbstate_t shiftState = mbstate_t();
setlocale(LC_ALL, "");
wcsrtombs(mbs, &str, sizeof(mbs), &shiftState);
return string(mbs);
}

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.