2014-07-24 56 views
4

我嘗試着寫一些wchar_t *到文件,但編譯後的程序的命令行輸出如下所示。當試圖寫希臘字符串時,程序基本上是掛起的。下面寫入wofstream會產生異常

#include <iostream> 
#include <stdio.h> 
#include <fstream> 
#include <wchar.h> 
using namespace std; 

int main(int argc, char **argv) 
{ 

    printf("%s\n",setlocale(LC_ALL,"")); 
    wofstream f("xxx.txt", ios::out); 
    if(f.is_open()) 
    { 
     try 
     { 
      f.write(L"good",4); 
      f.flush(); 
      f.write(L"καλημερα",8); 
      f.close(); 
     } 
     catch (int e) 
     { 
      cout << "An exception occurred. Exception Nr. " << e <<endl; 
     } 

     printf("hello world\n"); 
     return 0; 
    } 
} 

爲什麼

el_GR.UTF-8 
terminate called after throwing an instance of 'int' 
Ακυρώθηκε (core dumped) 

源代碼?

+0

這是一個錯誤,因爲沒有在輸入輸出流應該永遠拋出一個int。什麼是編譯器和整個系統?有警告嗎?源代碼的編碼是什麼?最後,'e'的價值是什麼? –

+0

e的值是20.我使用g ++編譯時沒有警告。這看起來應該是一種初始化。 –

回答

1

流不會從環境中獲取語言環境。 我addeed:

#include <locale> 
locale loc("el_GR.utf8"); 
f.imbue(loc); 

所以流現在持有使用(如果我說錯了請糾正)的語言環境。

能正確運行的代碼是:

#include <iostream> 
#include <stdio.h> 
#include <fstream> 
#include <wchar.h> 
#include <locale> 


using namespace std; 

int main(int argc, char **argv) 
{ 
    locale loc("el_GR.utf8"); 
    wcout<<"Hi I am starting Ξεκινάμε"<<endl; 
    cout<<"%s\n"<<setlocale(LC_ALL,"en_US.utf8")<<endl; 
    wofstream f("xxx.txt", ios::out); 
     if(f.is_open()){ 
      f.imbue(loc); 

      f.write(L"good",4);f.flush(); 
      f.write(L"καλημέρα",8); 
      f.close(); 
      cout<<"fileClosed"<<endl; 
    } 

    cout<<"hello world"<<endl; 
    return 0; 


} 
+0

您可以使用'getenv'從環境中獲取語言環境。 – Brian

+1

或者只是使用locale loc(setlocale(LC_ALL,「」))'將所有相關的環境考慮在內...... –

+0

我用f.imbue(locale(setlocale(LC_ALL,「」)));它的工作原理 –