C程序設計教學課件:Chapter 2 IO Streams_第1頁
C程序設計教學課件:Chapter 2 IO Streams_第2頁
C程序設計教學課件:Chapter 2 IO Streams_第3頁
C程序設計教學課件:Chapter 2 IO Streams_第4頁
C程序設計教學課件:Chapter 2 IO Streams_第5頁
已閱讀5頁,還剩31頁未讀 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

1、C+ ProgrammingChapter 2 I/O Streams as an introduction to Objects and ClassesIndex2.1 Streams and Basic File I/O2.2 Tools for streams I/O2.3 Character I/O2.4 InheritanceChap. 2 I/O Streams2.1 Streams and Basic File I/OStreams and basic file I/OStreams allow you to write programs that handle file inp

2、ut and keyboard input in a unified way, and that handle file output and screen output in a unified way.A stream is a flow of characters. If the flow is into your program, the stream is called an input stream. If the flow is out of your program, the stream is called output stream.If the input stream

3、flows from the keyboard, then your program will take input from the keyboard. If the input stream flows from a file, then your program will take its input from that file. Its Similar to output stream.Streams and basic file I/OThe cin is an input stream connected to the keyboard, and cout is an outpu

4、t stream connected to the screen.We can define other streams that come from or go to files; once we have defined them, we can use them in the same way we use the streams cin and cout. For example, a stream called in_stream is defined that comes from some file: int the_number; in_streamthe_number; An

5、 output stream named out_stream is defined that goes to another file: out_streamthe_number is the_numberendl;Once the streams are connected to the desired files, your program can do file I/O the same way it does I/O using the keyboard and screen.Why use files for I/OFiles provide you with a way to s

6、tore data permanently;You can create an input file for your program or read an output file produced by your program whenever its convenient for you, as opposed to having to do all your reading and writing while the program is running;Files also provide you with a convenient way to deal with large qu

7、antities of data.File I/OWhen your program takes input from a file, its said to be reading from the file; when your program sends output to a file, its said to be writing to the file;The method we will use reads the file from the beginning to the end. Using this method, your program isnt allowed to

8、back up and read anything in the file a second time, like the output to the screen.File I/OThe streams cin and cout are already declared for you, but if you want a stream to connect a file, you must declare it just as you would declare any other variable. The type for input-file stream variables is

9、named ifstream, and the type for output-file stream variables is named ofstream. ifstream in_stream; ofstream out_stream;The types ifstream and ofstream are defined in the library with the header file fstream. #include using namespace std;File I/OStream variables must each be connected to a file. Th

10、is is called opening the file and is done with a function named open. in_stream.open(infile.dat);If the input file is in the same directory as your program, you probably can simply give the name of the file. In some situations you might also to specify the directory that contains the file.File I/OOn

11、ce you have declared an input stream variable and connected it to a file using the open function, your program can take input from the file using the extraction operator . int one_number, another_number; in_streamone_numberanother_number;An output stream is used as the same way of the input stream.

12、ofstream out_stream; out_stream.open(outfile.dat); out_streamone_number = one_number another_number = another_number;File I/OEvery file should be closed when your program is finished getting input from the file or sending output to the file. Closing a file disconnects the stream from the file. A fil

13、e is closed with a call to the function close. in_stream.close(); out_stream.close();Check whether a file was open successfullyYou can use the member function named fail to test whether a stream operation has failed. There is a member function named fail for each of the classes ifstream and ofstream

14、.You should place a call to fail immediately after each call to open to check whether a file was opened successfully, the function fail will return true if the call to open fails.in_stream.open(stuff.dat); if(in_stream.fail() coutInput file openning failed.n; exit(1); Chap. 2 I/O Streams2.2 Tools fo

15、r streams I/OFormatting output with stream functionsThe layout of a programs output is called the format of the output. In C+ you can control the format with commands that determine such details as the number of spaces between items and the number of digits after the decimal point. cout.setf(ios:fix

16、ed); cout.setf(ios:showpoint); cout.precision(2);Formatting output with stream functionsEvery output stream has a member function named precision. When your program executes a call to precision, then from that point on in your program, any number with a decimal point that is output to that stream wi

17、ll be written with a total of two significant figures, of with two digits after the decimal point, depending on when your compiler was written.A call to precision applies only to the stream named in the call. If your program has another output stream out_stream_two, then you have to call the functio

18、n precision to effect on it.out_stream_two.precision(3);Formatting output with stream functionssetf is an abbreviation for setflags. A flag is an instruction to do something in one of two possible ways. If a flag is given as an argument to setf, then the flag tells the computer to write output to th

19、at stream in some specific way. What it causes the stream to do depends on the flag.Any flag that is set may be unset. To unset a flag, you use the function unsetf. cout.unsetf(ios:fixed);Formatting output with stream functionsFlagMeaningios:fixedFloating-point numbers are not written in e-notationi

20、os:scientificFloating-point numbers are written in e-notationios:showpointA decimal point and trailing zeros are always shown for floating-point numbersios:showposA plus sign is output before positive valuesios:rightThe next item output will be at the right end of the space specified by widthios:lef

21、tThe next item output will be at the left end of the space specified by widthFormatting Flags for setfFormatting output with stream functionsOne very commonly used formatting function is width. coutStart Now;cout.width(4);cout7endl;The output is: Start Now 7If the output required more space than you

22、 specified in the argument to width, then as much additional space as is needed will be used.A call to width applies only to the next item that is output. If you want to output 12 numbers, using 4 spaces to output each number, then you must call width 12 times.ManipulatorsA manipulator is a function

23、 that is called in a nontraditional way. In turn, the manipulator function calls a member function.Manipulators are placed after the insertion operator, just as if manipulator function call were an item to be output.Like traditional functions, manipulators may or may not have arguments.To use the ma

24、nipulators, you must include the following directive in your program: #include using namespace std;ManipulatorsInput and output can be formatted using manipulators. ManipulatorsEffectendlWrite new line and flush output streamdecInput or output in decimalhexInput or output in hexadecimaloctInput or o

25、utput in octalsetw(n)Set field width to nsetfill(c)Make c the fill characterleftLeft justifyrightRight justifyManipulatorsExample 1: int i=91;couti= i (decimal)n;couti= octi (octal)n;couti= hexi (hexadecimal)n;couti= deci (decimal)n;Output: i = 91 (decimal) i = 133 (octal) i = 5b (hexadecimal) i = 9

26、1 (decimal)ManipulatorsExample 2: float a=1.05, b=10.15, c=200.87;coutsetfill(*)setprecision(4);coutsetw(10)aendl;coutsetw(10)bendl;coutsetw(10)cnext;sum += next;count+;The average is sum/count+;double next, sum=0;int count=0;while(in_streamnext)sum+=next;count+;The average is sum/count.Chap. 2 I/O

27、Streams2.3 Character I/OCharacter I/OAll data is input and output as character data. When your program outputs the number 10, its really the two characters 1 and 0 that are output.However your program is written, the computer hardware is always reading the characters 1 and 0, not the number 10. This

28、 conversion between characters and numbers is usually done automatically so that you need not think about such detail.C+ provides some low-level facilities for input and output of character data. These low-level facilities include no automatic conversions.The member functions get and putThe function

29、 get allows your program to read in one character of input and store it in a variable of type char. Every input stream, whether it is an inputfile stream or the stream cin, has get as a member function.char next_symbol;cin.get(next_symbol);When you use the extraction operator, some things are done f

30、or you automatically, such as skipping blanks. With the member function get, nothing is done automatically.The member functions get and putIts important to note that your program can read any character in this way. If the next input character is a blank or a new-line character n, using get will not

31、skip over the character.char c1, c2, c3;cin.get(c1);cin.get(c2);cin.get(c3);If the input is: ABCDThen: c1=A; c2=B; c3=n;The member functions get and putOne thing you can do with the member function get is to have your program detect the end of a line.coutEnter a line of input and I will echo it:n;ch

32、ar symbol;docin.get(symbol);coutsymbol;while (symbol!=n);coutThats all for this demonstration;The member function put is analogous to the member function get except that its used for output rather than input. Put allows your program to output one character.Programming example Checking inputvoid get_

33、int(int& number)char ans;docoutnumber;coutYou entered numberans;new_line();while(ans!=Y)&(ans!=y);#include void get_int(int&);void main()int n;get_int(n);coutfinal value read is = nendl;void new_line()char symbol;docin.get(symbol);while(symbol!=n);The eof member functionEvery input-file stream has a member function called eof that can be used to determine when all of the file has been read and there is no more input left for the program.Since we usually want to test that we are not at the end of a file, a call to the eof is typically used with a not in front of it.Example

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論