在C++中读取文本文件

3
我正在尝试开发一个功能,检查用户输入的中文单词是否在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);

enter image description here


它是以哪种方式“不起作用”?请详细说明并发布一个[MCVE]。 - πάντα ῥεῖ
3个回答

2
如果您对更多细节感兴趣,请参阅stod-does-not-work-correctly-with-boostlocale,以获得有关locale如何工作的更详细说明。
简而言之,对您来说更有趣的部分是:
  1. std::stream (stringstream, fstream, cin, cout) 有一个内部区域对象,它与创建流对象时的全局C++区域值相匹配。由于std::in在您的代码中的main被调用之前就已经创建了,所以它很可能具有传统的C语言区域设置,无论您之后做什么。
  2. 您可以通过调用std::stream::imbue(std::locale(your_favorit_locale))来确保std::stream对象具有所需的区域设置。
我想添加以下内容:
  1. 几乎从来不将全局区域设置为好主意-它可能会破坏程序的其他部分或第三方库-你永远不知道。

  2. std::setlocalelocale::global做了稍微不同的事情,但locale::global不仅重置全局c++区域设置,还重置c区域设置(也由std::setlocale设置,不要与传统的"C"区域设置混淆),因此如果您想将c++区域设置设置为Chinese_China并将c区域设置设置为chinese-simplified,则应以另一种顺序调用它。

首先 locale::global(locale("Chinese_China")); 然后 setlocale(LC_ALL, "Chinese-simplified");

你好,有没有想法可以在创建了cout、stringstream等对象之后更改其内部locale对象?如何处理多个locales的情况? - BugShotGG
@BugShotGG 你可以使用 std::cout.imbue(...) - ead

1
尝试使用 locale::global(locale("Chinese_China.936"));locale::global(locale("")); 来设置区域设置。 对于 LC_ALL,请使用 "chinese-simplified""chs"

1

当我输入中文单词时,它无法工作。只有当我输入英文单词和数字时,它才能正常工作。 - mi ka

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接