2016-02-11 159 views
3

我想開發函數,檢查用戶輸入的中文單詞是否在txt文件中。以下是代碼。但它不起作用。我想知道問題是什麼。請幫幫我。閱讀txt文件在c + +(中文)

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

+0

它以哪種方式_isn't working_?請詳細說明併發布[MCVE]。 –

回答

1

嘗試locale::global(locale("Chinese_China.936"));locale::global(locale("")); 而對於LC_ALL "chinese-simplified""chs"

1

如果使用Vladislav's answer不解決這個問題,看看answerstl - 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。另見c++ - double byte character sequence conversion issue in Visual Studio 2015 - Stack Overflow

+0

當我輸入中文單詞時,它不工作。只有當我輸入英文單詞和數字時,它才起作用。 –

1

如果您有興趣瞭解更多詳情,請參閱stod-does-not-work-correctly-with-boostlocale了更詳細的描述瞭如何locale作品,

簡而言之適合你的更有趣的部分:

  1. std::streamstringstreamfstream,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");