한글 wstring을 string으로 변환

paek1ju의 이미지

안녕하세요. 한글 자판을 작성하고 있는 사람입니다. 저번주에 올린 질문에 이어 또 삽질하다 글올립니다..

제가 변경하고 있는 코드가 한글을 모두 wstring wstr (L"ㄱ"); 와 같은 wide string을 사용하게 되어 있습니다.
헌데 한글을 조합하기 위해서 wstring wstr (L"ㄱ"); 을 string str 으로 변경해서 사용해야 되는데요.

아래 코드에서 보면 string str ("ㄱ"); 의 경우 str.size() 가 3이고 이를 unsigned char로 변형하면 각 바이트가 227, 132, 177 이렇게 됩니다.

	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로 출력
	}
	/****************************************************************************************/
 
* 결과
str size 3
ㄱ
227
132
177

이런 형식으로 아래 코드와 같이 wstring 을 string으로 변환하여 "ㄱ" 을 3바이트로 문자로 접근하려고 합니다.
헌데 wstring 을 string 으로 변환하는 방법이 문제입니다. 인터넷에서 검색하여 알게된
여러가지 방법 wcstombs, wcs_to_mbs 등 사용하면 결과가 이상합니다.

wstring wstr (L"ㄱ") 을 어떻게 하면 string str("ㄱ") 과 같이 변환하여 사용할 수 있을까요?

	int i = 0;
 
	/****************************************************************************************/
	const unsigned char *ctemp;
	wstring wstr (L"ㄱ");
	string str;
 
	// wstring을 string으로 변환
	// str = wstr2str(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로 출력
	}
	/****************************************************************************************/

shint의 이미지

이렇게 나왔습니다.
맞는건지는 잘 모르겠네요. ㅇ_ㅇ;;;
Qt에서 빌드 되는것까지는 확인했습니다.

#include <QtCore/QCoreApplication>
#include <iostream>
#include <string>
#include <locale>
#include <cstdlib>
#include <QDebug>
 
 
#ifdef WIN32
  #pragma warning(disable:4786)
#endif
#include <iostream>
using namespace std;
 
void string2wstring(wstring &dest,const string &src)
{
     dest.resize(src.size());
     for ( unsigned int  i=0; i<src.size(); i++)
        dest[i] = static_cast<unsigned char>(src[i]);
}
 
void wstring2string(string &dest,const wstring &src)
{
     dest.resize(src.size());
     for (unsigned int i=0; i<src.size(); i++)
         dest[i] = src[i] < 256 ? src[i] : ' ';
}
 
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
 
    //한글 wstring을 string으로 변환'하기를 검색하면 이렇게 나오는데. 첫번째것이 되는거? 같습니다.
    //http://blog.naver.com/ratmsma/40034898566
    //http://blog.naver.com/pjy3124/120050002754
    //http://cafe.naver.com/newchany/625
 
    int i = 0;
    const unsigned char *ctemp;
    string str = "한글 English";
    wstring wstr;
 
    string2wstring( wstr, str );
    wstring2string ( str, 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로 출력
    }
 
 
    //http://www.freebsdchina.org/forum/viewtopic.php?t=34539
    wchar_t *wc;
    wchar_t *ws = (wchar_t*)"中文/Chinese";
 
     /*
    if(setlocale(LC_ALL, "zh_CN.UTF-8") == NULL){
      perror("set local failed");
      return 1;
    }*/
    setlocale(LC_ALL, "");
    wprintf(L"%ls\n\n", ws);
 
    for(wc = ws; *wc != 0; ++wc){
      wprintf(L"%lc\n", *wc);
    }
 
    //http://neptjuno.tistory.com/42
    //-finput-charset=charset 은 안되더군요. ㅇ_ㅇ;;
 
    return a.exec();
}

----------------------------------------------------------------------------
젊음'은 모든것을 가능하게 만든다.

매일 1억명이 사용하는 프로그램을 함께 만들어보고 싶습니다.
정규 근로 시간을 지키는. 야근 없는 회사와 거래합니다.

각 분야별. 좋은 책'이나 사이트' 블로그' 링크 소개 받습니다. shintx@naver.com

kukyakya의 이미지

잘못된 코드입니다. 해보진 않았지만 의도대로 동작할 것 같지 않군요.

wstring의 기반 자료형인 wchat_t 내에 유니코드 문자가 어떻게 인코딩될지는 표준에 명시되어 있지 않습니다.

string을 wstring으로 변환하기 위해선 일단 string내에 저장된 문자열의 인코딩을 먼저 파악하신 후에 iconv나 ICU를 이용하여 wstring으로 변환하시는 것이 가장 바람직할 것으로 보입니다.

C++11의 string conversion 표준 라이브러리는 아직 gcc에서 구현되지 않은 것 같고, VC 2010에는 구현이 되어있다고 들었습니다.

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.