[C++基礎]007_char、wchar_t、wcout、setlocale()

來源:互聯網
上載者:User
 1 #include<iostream> 2 using namespace std; 3  4 int main(){ 5     char ch1 = 'A'; 6     cout<<"ch1 = "<<ch1<<endl; 7  8     char ch2 = '中'; 9     cout<<"ch2 = "<<ch2<<endl;10 11     wchar_t ch3 = '中';12     cout<<"ch3 = "<<ch3<<endl;13 14     wchar_t ch4[] = L"中";15     cout<<"ch4 = "<<ch4<<endl;16 17     system("pause");18     return 0;19 }

上面的代碼會輸出什麼呢?自己看看再看下面的答案:

ch1 = Ach2 =ch3 = 54992ch4 = 0043F944請按任意鍵繼續. . .

我去!為什麼輸不了中文呢??

那要怎麼輸出呢!看下面的代碼吧!

 1 #include<iostream> 2 #include<locale> 3 using namespace std; 4  5 int main(){ 6     char ch1 = 'A'; 7     cout<<"ch1 = "<<ch1<<endl; 8  9     char ch2 = '中';10     cout<<"ch2 = "<<ch2<<endl;11 12     wchar_t ch3 = '中';13     cout<<"ch3 = "<<ch3<<endl;14 15     setlocale(LC_ALL, "chs");16     wchar_t ch4[] = L"中";17     wcout<<"ch4 = "<<ch4<<endl;18 19     system("pause");20     return 0;21 }

注意,我在最後一段輸出裡面加上了一句設定地區化的代碼,代碼被設定在中文環境中。同時,我用了wcout來輸出中文。

上面的程式輸出如下所示:

1 ch1 = A2 ch2 =3 ch3 = 549924 ch4 = 中5 請按任意鍵繼續. . .

沒有java和c#方便啊!不過挺好玩的,呵呵!

總結:

處理雙位元組字元方法如下

1. 設定地區,用setlocale()方法

2. 定義字元變數,方法見代碼

3. 用wcout輸出

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.