cout 輸出格式控制 還是要注意點

來源:互聯網
上載者:User

cout 輸出格式控制
  如果要在輸出資料流中加入格式控制符則要載入標頭檔:#include <iomanip>
     這裡面 iomanip 的作用比較多:
     主要是對 cin,cout 之類的一些操縱運運算元,比如 setfill,setw,setbase,setprecision 等等。它是 I
     /O 流量控制標頭檔,就像 C 裡面的格式化輸出一樣.以下是一些常見的控制函數的:
    dec 置基數為 10 相當於"%d"
    hex 置基數為 16 相當於"%X"
    oct 置基數為 8 相當於"%o"
    sample://作用永久
    cout<<12<<hex<<12<<oct<<12<<12;output 12c1414
    setprecision(n) 設顯示小數精度為 n 位 //作用永久
    sample: setf(ios:fixed);
    cout<<setprecision(2)<<2.345<<endl; ouput 2.34 //注意先用 setf(ios::fixed);否則結果自己測試下
    setw(n) 設域寬為 n 個字元 //作用臨時
     這個控制符的意思是保證輸出寬度為 n。如:
     cout<<setw(3)<<1<<setw(3)<<10<<setw(3)<<100;輸出結果為
     1 10100 (預設是靠右對齊)當輸出長度大於 3 時(<<1000),setw(3)不起作用。
     setfill(c) 設填充字元為 c
         setioflags(ios::fixed)固定的浮點顯示
         setioflags(ios::scientific) 指數表示
         sample cout<<setiosflags(ios::fixed)<<setprecision(2)<<2.345<<endl; output 2.34

         setiosflags(ios::left) 靠左對齊
         setiosflags(ios::right) 靠右對齊
         setiosflags(ios::skipws) 忽略前置空白
         setiosflags(ios::uppercase) 16 進位數大寫輸出
         setiosflags(ios::lowercase) 16 進位小寫輸出
         setiosflags(ios::showpoint) 強制顯示小數點
         setiosflags(ios::showpos) 強制顯示符號
         sample: cout<<setiosflags(ios::uppercase)<<hex<<12<<15<<endl; output CF
         cout<<setioflags(ios::showpoint)<<x<<endl;
         若 float x=1,則 output 1.000000 不使用直接輸出 1
     cout<<setiosflags(ios::showpos)<<1<<endl;output +1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.