Search code examples
c++locale

read txt file in c++ (chinese)


I'm trying to develop function that check whether chinese word which user enters is in the txt file or not. The following is the code. But it is not working. I want to know what the problem is. Help me please.

setlocale(LC_ALL, "Chinese-simplified");
locale::global(locale("Chinese_China"));
SetConsoleOutputCP(936);
SetConsoleCP(936);

bool exist = FALSE;

cout << "\n\n <Find the keyword whether it is in that image or not> \n ";
cout << "Enter word to search for: ";
wstring search;
wcin >> search; //There is a problem to enter chinese.

wfstream file_text("./a.txt");
wstring line;
wstring::size_type pos;

while (getline(file_text, line))
{
    pos = line.find(search);
    if (pos != wstring::npos) // string::npos is returned if string is not found
    {
        cout << "Found!" << endl;
        exist = true;
        break;
    }
}

when I use this code, The result is as follows.

const int oldMbcp = _getmbcp();
_setmbcp(936);
const std::locale locale("Chinese_China.936");
_setmbcp(oldMbcp);

enter image description here


Solution

  • Try locale::global(locale("Chinese_China.936")); or locale::global(locale("")); And for LC_ALL "chinese-simplified" or "chs"