版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 二手房协议购房
- 分家协议范本2025
- 2024版二手房房屋买卖合同协议15篇
- 工作领域2 新居住项目产品与价格策70课件讲解
- 2023年酒店、厨房设备用品项目融资计划书
- 2023年消化系统用药项目融资计划书
- 2023年全自动金属带锯床超精密加工机床项目融资计划书
- 【虎啸】2024年虎啸年度洞察报告-3C家电行业
- 机械制图考试题+答案
- 广东省茂名市高州市2023-2024学年八年级上学期期末考试数学试卷(含答案)
- 多元回归分析论文
- JGT388-2012 风机过滤器机组
- 传感器原理与应用智慧树知到课后章节答案2023年下山东大学(威海)
- 交安工程专项施工方案
- 部编人教版五年级上册语文 第19课 父爱之舟 说课稿
- 硅酸盐水泥的原料及配料计算课件
- (完整版)一年级最大能填几最小能填几
- 养老院工作人员保密协议书
- 无人生还-读书分享课件
- 壮族的服饰 壮族服饰特点
- 暴发性心肌炎-课件
评论
0/150
提交评论