我正在尝试开发一个功能来检查用户输入的中文单词是否在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);
如果您有兴趣了解更多详情,请参阅stod 无法正确使用 boostlocale https://stackoverflow.com/questions/34744911/stod-does-not-work-correctly-with-boostlocale/34761910#34761910更详细的说明locale
作品,
简而言之,对您来说更有趣的部分是:
-
std::stream
(stringstream
, fstream
, cin
, cout
) 有一个内部语言环境对象,它与全局 C++ 语言环境的值相匹配眼下流对象的创建。作为std::in
是在您的代码之前很久创建的main
被称为,它很可能具有经典的 C 语言环境,无论您之后做什么。
- 你可以确保
std::stream
通过调用,对象具有所需的语言环境std::stream::imbue(std::locale(your_favorit_locale))
.
我想补充以下内容:
设置全局区域设置几乎从来都不是一个好主意 - 它可能会破坏程序的其他部分或第三方库 - 你永远不知道。
std::setlocale
and locale::global
做稍微不同的事情,但是locale::global
不仅重置全局 c++ 语言环境,还重置 c 语言环境(也由std::setlocale
,不要与经典的“C”语言环境混淆),因此如果您希望将 c++ 语言环境设置为Chinese_China
和 C 语言环境到chinese-simplified
第一的locale::global(locale("Chinese_China"));
然后setlocale(LC_ALL, "Chinese-simplified");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)