c++读取txt文件(中文)

read txt file in c++ (chinese)

我正在尝试开发功能来检查用户输入的中文单词是否在 txt 文件中。以下是代码。但它不起作用。我想知道问题是什么。请帮助我。

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;
    }
}

当我使用这段代码时,结果如下。

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

尝试locale::global(locale("Chinese_China.936"));locale::global(locale("")); 对于 LC_ALL "chinese-simplified""chs"

如果使用 does not solve this, take a look at answer to stl - Shift-JIS decoding fails using wifstrem in Visual C++ 2013 - Stack Overflow:

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

似乎有 a bug in Visual Studio's implementation of locales. See also c++ - double byte character sequence conversion issue in Visual Studio 2015 - Stack Overflow

如果您对更多详细信息感兴趣,请参阅 以了解有关 locale 工作原理的更详细说明,

简而言之,对您来说更有趣的部分是:

  1. std::stream (stringstream, fstream, cin, cout) 有一个内部语言环境对象,匹配全局 C++ 的值创建流对象时 的语言环境。由于 std::in 是在调用 main 中的代码之前很久创建的,因此无论您之后做什么,它很可能具有经典的 C 语言环境。
  2. 您可以通过调用 std::stream::imbue(std::locale(your_favorit_locale)).
  3. 来确保 std::stream 对象具有所需的语言环境

我想补充以下内容:

  1. 设置全局语言环境几乎不是一个好主意 - 它可能会破坏程序的其他部分或第三方库 - 你永远不知道。

  2. std::setlocalelocale::global 做的事情略有不同,但是 locale::global 不仅重置了全局 c++-locale,还重置了 c-locale(这也是由 std::setlocale 设置,不要与经典的 "C" 语言环境混淆),因此如果您希望将 C++ 语言环境设置为 Chinese_China 并将 C 语言环境设置为 chinese-simplified

首先 locale::global(locale("Chinese_China"));

而且比 setlocale(LC_ALL, "Chinese-simplified");