locale을 적용하지 않은 경우:

#include <iostream>
#include <string>
#include <algorithm>
 
int main()
{
  std::string s;
  std::getline(std::cin, s);
  std::reverse(s.begin(), s.end()); // modifies s
  std::cout << s << std::endl;
  return 0;
}

 

컴파일:

$ g++ -o testReverseUTF8_003 testReverseUTF8_003.cpp

실행:

$ ./testReverseUTF8_003
안녕하세요?
?▒▒츄옕핅눕▒

 

locale을 적용하고 wstring, wcout, wcin을 사용한 경우:

#include <iostream>
#include <string>
#include <algorithm>
 
int main()
{
  std::setlocale(LC_ALL, "ko_KR.UTF-8");
  std::wstring s;
  std::getline(std::wcin, s);
  std::reverse(s.begin(), s.end()); // modifies s
  std::wcout << s << std::endl;
  return 0;
}

 

컴파일:

$ g++ -o testReverseUTF8_003 testReverseUTF8_003.cpp

실행:

$ ./testReverseUTF8_003
안녕하세요?
?요세하녕안


 

 

 

Posted by Scripter
,

다음은 utf-8 인코딩으로 저장한 C++ 소스이다.

Cygwin의 g++ tkdyd tl,  만일  아래의 소스에서
        std::setlocale(LC_ALL, "ko_KR.UTF-8");
대신  
        std::locale::global (std::locale ("ko_KR.UTF-8"));
로 하면 캄핑ㄹ은 되지만 실행 시에

        Segmentation fault (core dumped)

에러가 난다.

* 소스 파일명: testLocale_003.cpp

// Filename: testLocale_003.cpp
//
// Compile:  g++ -std=c++11 -o testLocale_003 testLocale_003.cpp
//    or         g++ -std=c++0x -o testLocale_003 testLocale_003.cpp
//    or         g++ -o testLocale_003 testLocale_003.cpp

#include <iostream>
#include <locale>
#include <cstring>   // for strlen()

using namespace std;

int main() {
  //// std::locale::global (std::locale ("ko_KR.UTF-8"));
  std::setlocale(LC_ALL, "en_US.UTF-8");
  wcout << L"한글\n";
  wcout << wcslen(L"한글") << L"\n";
  wcout << L"韓國語\n";
  wcout << wcslen(L"韓國語") << L"\n";

  cout << u8"한글\n";
  cout << strlen(u8"한글") << "\n";
  cout << u8"韓國語\n";
  cout << strlen(u8"韓國語") << "\n";
}

 

위의 소스에서 처럼 u8"스트링" 구문을 사용하면, g++ 명령으로 컴파일 시에 -std=c++11 또는 -std=gnu11 옵션을 주어야 한다.

 

* 컴파일

$ gcc -std=c++11 -o testLocale_003 testLocale_003.cpp

* 실행

$ ./testLocale_003

한글
2
韓國語
3
한글
6
韓國語
9

 

Posted by Scripter
,