C++ IO 詳細用法

http://www.cnblogs.com/keam37/ keam全部 轉載請註明出處html

本文將分別從<iostream>,<sstream>,<fstream>,<iomanip>4個頭文件介紹包含在其中的函數的用法.ios

#inclde<iostream>c++

    cin,cout,cerr是最基本的輸入輸出流 ,經過運算符"<<"和 「>>」操做緩存

    例如從鍵盤讀入兩個字符串,再將其合併輸出app

string s1,s2;

cin>>s1>>s2;

cout<<s1+' '+s2;

if(!cin)

cerr<<"input error";

 

  運行輸入爲 :函數

Hellospa

keambar3d

  則會輸出:指針

Hello keambarcode

若是直接輸入文件結束符   ctrl+z

        則會輸出 「input error」

 

這裏與if(!cin) 有關的是操縱流的條件狀態

有如下幾種狀態(flag)

badbit           表明流已經崩潰

failbit            表示一個IO操做失敗

eofbif           表示流到達文件結束

goodbit       值爲0, 表示沒有錯誤

定義 istream s;//s是一個輸入流

s.bad()               對應badbit,若是badbit置位,返回true;

s.eof()                對應eofbit狀態,如上;

s.fai()                 對應failbit,如上;

s.good()            對應goodbit,如上;

s.clear()             復位全部錯誤狀態,若是加上參數如s.clear(failbit)則僅復位failbit;

s.setstate(flag)  將流s的狀態復位爲給定狀態;

s.rdstate()          返回當前s流的狀態,返回值爲 flag;

下面的例子來自C++primer:

 

auto old_state = cin.rdstate(); //記住cin的當前狀態

cin.clear(); //使cin有效

process_input (cin); //使用cin

cin.setstate (old_state) ; //將cin置爲原狀態

若是程序崩潰,輸出緩衝區將不會刷新,可能致使不會輸出程序執行結果.

 

刷新輸出緩衝區的方法

cout<<」hi」<<endl;  輸出字符串加上換行,而後刷新;

cout<<」hi」<<flush;輸出字符串,而後刷新;

cout<<」hi」<<ends;輸出字符串加上一個空字符,而後刷新;

   unitbuf 操做符

   cout<<unitbuf //全部輸出操做後都會當即刷新;

   cout<<nounitbuf //取消上述操做

關聯輸入和輸出流

默認狀況下 cin和cerr 都關聯到cout,所以讀cin或寫cerr 都會刷新cout;

x.tie(&O)             將x關聯到輸出流O;

x.tie()                   返回x當前關聯的輸出流指針,若沒有關聯到輸出流則返回空指針;

其餘操做

cout.put(char ch)                                             //將字符ch加入輸出流

cin.putback(char ch)                                      //將字符ch加入輸入流;

cin.get(char *s,streamsize num,char delim)//從cin流讀入字符串,從字符串的首指針,長度爲num,或讀到 delim結束,第三個參數可不帶

getline(cin,string s,char delim)                   //從cin流讀入一行,放入字符串中,遇到行結束或讀到delim結束,默認delim=‘\n’

cin.ignore( streamsize num=1, int delim ); //從cin流讀入數,長度爲num,或讀到delim結束,默認爲換行;

 

//在使用get後可使用 cin.gcount( )返回 已經讀入的字符數

    例如

 

char c[10];

cin.get ( &c[0], 9 );

cout << c << endl;

cout << cin.gcount( ) << endl;

/*==============================/*

#include<sstream>

  stringstream s;//定義一個字符串流s

  stringstream s(「keambar」);//定義一個已近寫入」keambar」的字符串流;

     s>> 從字符串s讀入數據

     s<<將字符寫入s;

  sstream操做雖然簡單,但十分實用,具體用法和方便之處自行體會 :)

<iostream>大部分輸入輸出操做均可以對stringstream使用

/*==============================/*

#inclde<fstream>

    ifstream read("in.txt");    //打開文件in.txt
    ofstream write("out.txt");//打開文件out.txt 若無則將建立

   read>>    //從文件讀入

   cout<<    //輸出到文件

   read.close();// 關閉與read綁定的文件;

   read.open("in2.txt");//從新將read與in2.txt綁定;

   read.is_open()//返回bool值,指出與s綁定的文件是否已近打開;

文件模式(mod)s.open(文件名,mod)

  in                 以讀方式打開

  out              以寫方式打開

  app             每次寫操做定位到文件末尾

  ate               打開後定位到文件末尾

  trunc           截斷文件

  binary          以二進制方式打開

默認使用oftream    以out方式打開,而且截斷文件,要保留原內容須要用app模式

下面內容來自文檔     seekg()/seekp()與tellg()/tellp()的用法詳解

seekg()/seekp()與tellg()/tellp()的用法詳解

對輸入流操做:seekg()與tellg()

對輸出流操做:seekp()與tellp()

下面以輸入流函數爲例介紹用法:

seekg()是對輸入文件定位,它有兩個參數:第一個參數是偏移量,第二個參數是基地址。

對於第一個參數,能夠是正負數值,正的表示向後偏移,負的表示向前偏移。

而第二個參數能夠是:

ios::beg:表示輸入流的開始位置

ios::cur:表示輸入流的當前位置

ios::end:表示輸入流的結束位置

tellg()函數不須要帶參數,它返回當前定位指針的位置,也表明着輸入流的大小。

其餘操做

peek()  //peek函數用於讀取並返回下一個字符,但並不提取該字符到輸入流中,也就是說,依然讓該字符做爲將要提取到輸入流的下一個字符。

例以下面來自 http://www.cplusplus.com/reference/istream/istream/peek/的例程

// istream::peek example

#include <iostream> // std::cin, std::cout

#include <string> // std::string

int main () {

	std::cout << "Please, enter a number or a word: ";

	char c = std::cin.peek();

	if ( (c >= '0') && (c <= '9') )

	{
              int n;

		std::cin >> n;

		std::cout << "You entered the number: " << n << '\n'; 15
	}
	else
	{

		std::string str;

		std::getline (std::cin, str);
		
		std::cout << "You entered the word: " << str << '\n';
	}
	return 0;

}

cin.read(char* buffer, streamsize num ) //按字節讀入

cin.write(const char* buffer, streamsize num )//按字節輸出

例如

struct {

       int height;

	int width;

} rectangle;

input_file.read ( (char *) (&rectangle), sizeof (rectangle) );

if ( input_file.bad() ) {

	cerr << "Error reading data" << endl;

	exit ( 0 );

}

/*==============================/*

#inclde<iomanip>

涉及到格式化輸出,不單單使用<iomanip>頭文件,也將包含<iostream>

<iostream>中有

cout.fill(char ch)                         // 將填充字符設置爲 ch

cout.fill()                                     //返回當前填充字符

cout.width(int k)                       //將輸出寬度設置爲k,設置僅對下次輸出有效

例如

 

cout << 32 << endl;

cout.width (5);

cout << 32 << endl;

cout << 32 << endl;

cout.fill ('#');

cout.width (5);

cout << 32 << endl;

cout << cout.fill() << endl;

 

將輸出

32
       32
32
###32
#

cout.flags()         //返回int值,表示當前格式

cout.precision(int k) //保留k位有效數字,不加參數返回int值,表示當前設置

cout.setf(ios::   )  //開啓格式 flag

ios格式

boolalpha          //按bool值輸出"true" 或 "false".

dec                     //以10進制輸出.

hex                    //以16進製表示整數.

oct                   //以8進製表示整數

fixed                  //將符點數按照普通定點格式處理(非科學計數法)

internal            //在符號位和數值的中間插入須要數量的填充字符以使串兩端對齊

left                   //在串的末尾插入填充字符以使串居左對齊

right                //在串的前面插入填充字符以使串居右對齊

scientific        // 將符點數按照科學計數法處理(帶指數域)

showbase      //爲整數添加一個表示其進制的前綴

showpoint     //在浮點數表示的小數中強制插入小數點(默認狀況是浮點數表示的整數不顯示小數點)

showpos        //強制在正數前添加+號

skipws            //忽略前導的空格

unitbuf           //前面已近介紹過,在插入(每次輸出)操做後清空緩存

uppercase     //強制大寫字母

下面來自http://www.cnblogs.com/devymex/archive/2010/09/06/1818754.html

更多操做也可參考其中

以上每一種格式都佔用獨立的一位,所以能夠用「|」(位或)運算符組合使用。調用setf/unsetf或flags設置格式通常按以下方式進行:

cout.setf(ios::right | ios::hex); //設置16進制右對齊

cout.setf(ios::right, ios::adjustfield); //取消其它對齊,設置爲右對齊

setf可接受一個或兩個參數,一個參數的版本爲設置指定的格式,兩個參數的版本中,後一個參數指定了刪除的格式。三個已定義的組合格式爲:

  • ios::adjustfield  對齊格式的組合位
  • ios::basefield  進制的組合位
  • ios::floatfield  浮點表示方式的組合位

另外

         cout.flag的操做有以下用法

int number = 32;
cout.setf (ios::showbase); //設置爲顯示進制前綴
//setw()函數在<iomanip>中,包括直接使用<<hex
cout << setw (6) << hex << 32 << setw (6) << oct << 32 << endl; 
cout << number << endl;//此時輸出按照最近一次輸出的格式輸出
auto p = cout.flags();//用p記錄當期的格式 cout.unsetf(ios::oct);//取消8進制輸出
cout << number << endl;
cout.flags (p); //設置爲格式p
cout << number << endl;
return 0;

 

輸出爲

0x20    040
040
32
040

參考資料 c++ primer,c++ Reference

相關文章
相關標籤/搜索