IO of C and C printf and scanf

  • Slides: 15
Download presentation
I/O of C and C++

I/O of C and C++

printf and scanf of C • Should add <stdio. h> • printf (“control string”,

printf and scanf of C • Should add <stdio. h> • printf (“control string”, exp 1, exp 2, …) • Scanf(“control string”, &var 1, &var 2, …)

Min. GW C/C++ types Type int long (int) unsigned (int) short (int) unsiged short

Min. GW C/C++ types Type int long (int) unsigned (int) short (int) unsiged short (int) char float # of bytes 4 4 4 range -2147483648~2147483647 0~4294967295 2 2 -32768~32767 0~65535 1 4 0~255 1. 2 e-38~3. 4 e 38

C++ I/O • Should add #include <streamio. h> • cout: console output • cin:

C++ I/O • Should add #include <streamio. h> • cout: console output • cin: console input • cerr: console error output (no buffer) • clog: console buffered output • E. G. : redirection will not affect cerr $My. Program>data

C++ I/O manipulator • Should add #include <iomanip. h> • dec: 10進位輸出(預設) • hex:

C++ I/O manipulator • Should add #include <iomanip. h> • dec: 10進位輸出(預設) • hex: 16進位輸出 • oct: 8進位輸出 • endl: ‘n’ • ends: ‘’ • flush: 將緩衝區資料全部送出 • E. G. : cout<<“Dec: ”<<100<<“, ”<<200<<endl <<“Hex: ”<<hex<<100<<“, ”<<200<<endl <<“Oct: ”<<oct<<100<<“, ”<<200<<endl

C++ I/O manipulator • setbase(int n): 設基底 – – n=0 default (10進位) n=8 (8進位)

C++ I/O manipulator • setbase(int n): 設基底 – – n=0 default (10進位) n=8 (8進位) n=10 (10進位) n=16 (16進位) • setw(int w): 設寬度 • E. G. : int size=20; char a[size]; cin>>setw(size)>>a;

C++ I/O manipulator • setfill(int c): 設填充字元 • E. G. : cout<<“ 1234567890”<<endl; cout<<setw(10)<<setfill(‘*’)<<“abc”;

C++ I/O manipulator • setfill(int c): 設填充字元 • E. G. : cout<<“ 1234567890”<<endl; cout<<setw(10)<<setfill(‘*’)<<“abc”; • Outcome: 1234567890 *******abc

C++ I/O manipulator • setprecision(int n): 設定浮點數精準度位數, 預設 6位 • E. G. : cout<<1.

C++ I/O manipulator • setprecision(int n): 設定浮點數精準度位數, 預設 6位 • E. G. : cout<<1. 234<<“, ”<<setprecision(2)<<1. 23 4 <<“, ”<<3. 456; • Outcome: 1. 234, 1. 2, 3. 5

C++ I/O manipulator • • fill(char): 設定填充字元,並回傳先前填充字元 fill(): 回傳先前填充字元 precision(int) precision() width(int) width() E.

C++ I/O manipulator • • fill(char): 設定填充字元,並回傳先前填充字元 fill(): 回傳先前填充字元 precision(int) precision() width(int) width() E. G. : cout. width(10); cout. fill(‘*’); cout<<“Good”; cout<<cout. fill(); • Outcome: ******Good*

C++ I/O manipulator • write(const char *str, int len): 輸出字串 • put(char): 輸出一字元 •

C++ I/O manipulator • write(const char *str, int len): 輸出字串 • put(char): 輸出一字元 • E. G. : char s[]="123456789"; s[4]=0; cout<<s<<endl; cout. write(s, 8)<<endl; cout. put('a'). put('b'). write("abcdefg", 4)<<endl; • Outcome: 1234 678 ababcd