Can't I enter hangeul with std::cin?

Viewed 56

I'm working at a super-simple program that if we enters a name, and it prints the entered name. It's easy but the problem is I live in korea and it's the hangeul(korean alphabet) so it must support hangeul

I tried this code:

#include <iostream>
#include <string>

using namespace std;

int main () {
    string name = "";
    cout << "이름을 입력하세요: "; getline(cin, name);
    cout << "당신의 이름은 " << name << "입니다.";
    return 0;
}

If we make it to english it will be:

#include <iostream>
#include <string>

using namespace std;

int main () {
    string name = "";
    cout << "Enter your name: "; 
    getline(cin, name);
    cout << "Your name is " << name << ".";
    return 0;
}

Looks easy. but if we put the hangeul in that cin,

Print:

Enter your name: 이름
Your name is .

and it just end. Of course the answer I wanted is:

Print:

Enter your name: 이름
Your name is 이름.

I've tried everything like using wide-character, change system locale and other many thing. Here's the code I've tried:

#include <iostream>
#include <string>

using namespace std;

int main () {
    setlocale(LC_ALL, "Korean");

    string name = "";
    cout << "이름을 입력하세요: "; 
    getline(cin, name);
    cout << "당신의 이름은 " << name << "입니다.";
    return 0;
}
#include <iostream>
#include <string>

using namespace std;

int main () {   
    wstring name = "";
    cout << "이름을 입력하세요: "; 
    getline(wcin, name);
    wcout << "당신의 이름은 " << name << "입니다.";
    return 0;
}
#include <iostream>
#include <string>

using namespace std;

int main () {   
    wstring name = "";
    cout << "이름을 입력하세요: "; 
    getline(wcin, name);
    cout << "당신의 이름은 ";
    wcout << name;
    cout << "입니다.";
    return 0;
}

If you can, please help me!

1 Answers
  1. Try to check return value of the setlocale function, if it returns null, than it simply fails, if so try to search for another names for Korean system locale.
  2. If you don't get an error in first paragraph, then check your comand prompt locale: press Windows+R, type 'cmd' and press Enter. In opened command prompt window type 'chcp' and press Enter. You should see output as shown below:
C:\Users\User>chcp
Active code page: 1251

1251 - this is mine coding page, means 'windows cp-1251'. After that google your coding page (you can find tables where each symbol placed with it's decimal representation on internet).

  1. Compare some Korean symbol from your program with it's representation from coding table, you can output first symbol's decimal value like this:
int main () {
    string name = "";
    cout << "이름을 입력하세요: " << endl; 
    getline(cin, name);
    cout << (int)name[0] << endl;
    return 0;
}

If the number you get from program differs from coresponding number from your codding page, then you definitely need to search for another locale to set in your program, or to change the locale in your terminal.

Related