0% found this document useful (0 votes)
2 views

Console I_O operations

Unit 8 covers Console I/O operations in C++, detailing the C++ stream system, including formatted and unformatted I/O operations. It explains the differences between the old and new C++ I/O libraries, the use of stream classes, and the significance of manipulators for managing output. The unit also discusses the advantages and disadvantages of formatted versus unformatted I/O, and provides examples of input and output operations using stream insertion and extraction operators.

Uploaded by

Heureuse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2 views

Console I_O operations

Unit 8 covers Console I/O operations in C++, detailing the C++ stream system, including formatted and unformatted I/O operations. It explains the differences between the old and new C++ I/O libraries, the use of stream classes, and the significance of manipulators for managing output. The unit also discusses the advantages and disadvantages of formatted versus unformatted I/O, and provides examples of input and output operations using stream insertion and extraction operators.

Uploaded by

Heureuse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 25
Notes Unit 8: Console I/O Operations Structure 81 Introduction 82 C++ Stream 83. C++ Streams classes 84 Formatted and Unformatted VO operations €.5 Managing Output with Manipulators 86 Summary &7 Check Your Progress 88 Questions and Exercises a9 KeyTems 810 Further Readings Objectives After studying this unit, you should be able to © Understand G++ stream © Discuss the concept of C++ stream classes. Explain the concept of Formatted and Unformatted I/O operations. @ Understand the concept of Managing Output with Manipulators. 8.1 Introduction C++ supports two VO systems: the one which is inherited from C and other is the object-oriented 1/0 system, whieh is charactenzed by C++. The different aspects of CH's I/O system, such as console I/O and disk /O, are actually just different perspectives on the same mechanism. This chapter discusses the foundations of the C++ /O system. Although the examples in this chapler use “console” I/O, the information is applicable to other devices, including disk fles. In the C= programming language, Inpuvoutput library refers functions in the C++ Standard Library which are implementing on stream-based input/output capabilities It is an object-oriented alternative to C’s FILE-based streams from the C standard library 8.2 C+ Stream There are currently two versions of the C++ object-oriented /O library in use: the older tone that is based upon the original specifications for C++ and the newer one defined by Standard C++. The old 1/0 library is supported by the header file . The new U/O library is supported by the header . For the most part the two libraries: appear the same, because the new 1/0 library is simply an updated and improved version of the old one. In fact, the vast majority of differences between the two occur beneath the surface, in the way that the libraries are implemented—not in how they are used From the programmers perspective, there are two main differences between the old and new C++/0 libraries. First, the new /O library contains a few additional features and defines some new data types. Thus, the new I/O library is essentially a superset of Console 10 Operations, Files the old one. Nearly all programs ariginally written for the old library will compile without substantive changes when the new library is used. Second, the old-style /O library was in the global namespace. The new-styie library is inthe std namespace. 8.3 C++ Streams classes A stream is a source of sequence of bytes. A stream abstracts for input/output devices, It ean be tied up with any iO device and VO can be performed in a uniform way. The C++ fostream library 1s an object-oriented implementation of this abstraction. It has a source (producer) of flow of bytes and a sink (consumer) of the bytes. The required Classes for the stream I/O are defined in different library header files. To use the (0 streams in a C++ program, one must include iostream.h header fle in the program. This fle defines the requited classes and provides the buffering. Instead of functions, the library provides operators to carry out the VO. Two of the Stream Operators are: <<: Stream insertion for output. >>. Stream extraction for input ‘The following streams are created and opened automatically. cin Standard console input (keyboard) cout Standard console output (screen) pan Standard printer (LPT) com Standard error output (screen). clog Standard log (screen) caux Standard auxiliary (screen), Example: The following program reads an integer and prints the input on the console +#include (/ Header for stream VO. int main(void) « Int p;// variable to hold the input integer cout << "Enter an integer: cin>> p: cout <<"In You have entered” << p; } 8.4 Formatted and Unformatted I/O operations Unformatted Input/Output is the most basic form of inputfoutput As Unformatted inputoutput transters the intemal binary representation of the data directly between memory and the file (On the other hand, Formatted output converts the internal binary representation of the data to ASCII characters which are written to the output fle Formatted input reads characters trom the input file and converts them to internal form. Formatted /O can be either "Free" format or “Explicit” format. 179 Notes 180 Notes (Object Oriented Programmimg with C+ Advantages and Disadvantages of Unformatted 10 Unformatted inputioutput is the simplest and most efficient form of inputioutput [tts usually the most compact way to store data Unformatted inputioutput is the least portable form of input/output Unformatted data files can only be moved easily to and from computers that share the same internal data representation © Unformatted input/output is not directly human readable, so you cannot type it out ona terminal screen or edit it wth a text editor. Advantages and Disadvantages of Formatted 1/0. ‘© Formatted inputioutput is very portable ‘© Itisa simple process to move formatted data files to various computers. © Formatted files are human readable and can be typed to the terminal screen or edited with a text editor. C++ 10 are based on streams, which are sequence of bytes flowing in and out of ‘the programs (just like water and oil flowing through pipe). In input operations, data bytes flow from an input source (such as keyboard, file, network or another program) into the program. In output operations, data bytes flow from the program to an output sink (such as console, file, network or another program) Streams acts a5 an intermediaries between the programs and the actual IO devices, in such the way that frees the programmers from handling the actual devices, so as to archive device independent IO operations Input Source (Keyboard, fil Input Stream |_Detwark program) (C++ Program = = — i Output Sink ] — (console, file, ‘Output Stream | network, program) Internal Data Formats: External Data Formats: * Text:char, wchar_t — * Textin various encodings = int, float, double, (US-ASCII, 1S0-8859-1, UCS-2, UTF-8, etc. UTF-16, UTF-26BE, UTFIG-LE, ete.) = Binary (raw bytes) C++ provides both the formatted and unformatted 10 functions. In formatted or high-level 10, bytes are grouped and converted to types such as int, double, string or user-defined types. In unformatted or low-level |O, bytes are treated as raw bytes and unconverted. Formatted 10 operations are supported via overloading the stream Insertion (<<) and stream extraction (>>) operators, which presents a consistent public 10 interface. To perform input and output, a C++ program 1. Construct a stream abject, 2 Connect (Associate) the stream object to an actual IO device (2.g., keyboard, console, file, network, another program) Console 10 Operations, Files 3. Perform inputfoutput operations on the stream, via the functions defined in the stream's pubic interface in a device independent manner. Some functions convert the data between the external format and intemal format (formatted IO); while ather does not (unformatted or binary 10) Disconnect (Dissociate) the stream to the actual 1O device (e g., close the file) 5. Free the stream object. C++ 10 Headers, Templates and Classes Headers C++ 10 is provided in headers (which included , , costream and ), (for fle |0), and csetrean> (for string 10). Furthermore, the header i ay | (sine Setprecteton Ea i senng oe aa ! —— vender (a tenvinte ce vet t lastantiation Template Classes In order to support various character sets (char andwchar_t in C++98/03: and charié_t, char32_+ introduced in C++11), the stream classes are written as template classes, which could be instantiated with an actual character type. Most of the template classes take two type parameters, For example, 22 basic_istream; emplate < art, class tra! class basic_ostream: 181 Notes 182 Notes ‘Object Oriented Programming wit C+ where © charT is the character type, such as char of wchar_t) © traits, of another template class char_traits, defined the properties of the character operations such as the collating sequence (sorting order) of character sot Template instantiations and typedef ‘As mention, the basic_oex template classes can be instantiated with @ character type, such as char and wchar_t. C+= further provides typedef statements to name these classes istream: ostream; jostrean: streambut; eanbut Specialization Classes for char type We shall focus on the specialization classes for char type! (© os base and ios: superclasses to maintain common stream properties such as format fag, field width, precision and locale. The superclass ios_base (which is not a tomplate class) maintains data that is independant of the template parameters, whereas the subclass ios (instantition of template basic ios) maintains data which is dependent ofthe template parameters. # istream (basic_istrean), ostream (basic_ostream): provide the input and output public interfaces. © ostream (basic iostream) subclass of both istream and ostrean, which supports bidirectional input and output operations. Take note thal istream and ostream are unidirectional streams, whereas fostream is bidirectional basic_iostrean template and iostrean class is declared in the cistream> header, nol ciostreaa> header 4 ifsteean, ofstresmand fetream for fle input, oulput and bidiectionsl inputioutput 4 istringstrean, ostringstrean and stringstream for string bulfer input, output and bidirectional inpuvoutput © streanbuf, Filebuf and stringbuf provide memory buffer for the stream, fils- stream and string-stream, and the public interface for accessing and managing the buffer. Console YO Operations Files Buttered 10 [Topo] The header also included the these headers: , and Hence, your program needs to include only the header for 1O operations. The header declares these standard stream objects: © cin (of istream class, basic_istream specialization), uein (of wistream ¢ lass, basic_istream specialization) corresponding 10 the standard input stream, detauited to keyword © cout (of ostream class), weout (of wostrean class): corresponding to the standard output stream, defauited to the display console. © corr (of ostream class), weer (of wostream class): corresponding to the standard error stream, defaulted to the display console © clog (Of ostrean class), welog (of wostrean class): corresponding to the standard {og stream, defaulted to the display console ‘The Stream Insertion << and Stream Extraction >> Operators Formatted output is cared out on streams via the stream insertion << and stream extraction >> operators. For example << value; cin >> variable: Take note thet cin/cout shall be the left operand and the data flow in the direction of the arrows: The << and >> operators are overloaded to handle fundamental types (such a5 int and double), and classes (such as string) You can also overload these ‘operators for your own user-defined types The cin << and cout >> retum a reference to cin and cout, and thus, support cascading operations. For example, cout << valued << valued << cin >> variabiet << variable? << The ostream Class The ostream class is a typedef tO basic _ostream¢char> It contains two set of ‘output functions: formatted output and unformatted output. © The formatted output functions (via overloaded stream insertion operator <<) convert numeric values (such as int, double) from their internal representations (eg,, 16-/32-bit int, 64-bit double) to a stream of characters that representing the umaric values in text form, © The unformatted output functions (@.g., put(), wnite()) outputs the bytes as they are, without format conversion. 183 Notes 184 Notes ‘Object Oriented Programming wit C+ Formatting Output via the Overloaded Stream Insortion << Operator The ostream class overloads the stream insertion << operator for each of the G++ fundamental types (char, unsigned char, signed char, short, unsigned short, int, unsigned int, long, unsigned long, long long (C+*11), unsigned ong long (C++11), Float, double and long double It converts a numeric value from its internal representation to the text form ostream & operatorc< (type) // type of int, double etc The << operator retums a reference to the invoking ostream object. Hence, you can concatenate << operations, eg, cout << 123 << 1.13 <« endl; The <« operator is also overloaded for the following pointer types: * const char *, const signed char *, const unsigned chan *: for outputting C-strings and literals. It uses the terminating null character to decide the end of the char array. © void © can be used to print an address For example, Flushing the Output Buffer ‘You can flush the output butter vie 1. flush member function or manipulator 2. // Member function of ostream class - std::ostreanm::flush 3. ostream & flush (); 4. // Example 5. cout <« “hello”; 6. cout. flush(); 7. // Manipulator ~ std::flush 8. ostream & flush (ostream & os); 8. // Example cout << “hello” << flush: 49. end manipulator, which inserts a newline and flush the buffer. Outputting @ newline character *\n' may not flush the output buffer; but end does, 11. // Manipulator - std::endl ostream & end (ostream & os) Console 10 Operations, Files 12. ein output buffer is Mushed when input is pending, e g., 13. cout <<"Enter a number: " 14. int number, cin << number // flush output buffer so as to show the prompting nessage The Istream class Similar to the ostream class, the istreamclass 1S atypedef to basic_istream. It also supports formatted input and unformatted input © In formatting input, via overloading the >> extraction operator, it converts the text form (a stream of character) into internal representation (such as 16-/32-bit int, 64. byte double). © In unformatting input, such as get(), getlin(), read(), it reads the characters as they are, without conversion. Formatting Input via the Overloaded Stream Extraction >> Operator ‘The istreamclass overloads the extraction >> operator for each of the C++ fundamental types (char, unsigned char, signed _ char, short, unsigned short int, unsigned int, long unsigned long long lang (C+#11) unsigned long long (C++11), float, double and long double It performs formatting by converting the inout texts into the internal representation of the respective types. istream & operator<< (:y; int, double ste. ‘The >> operator returns a reference to the invokind istream object. Hence, you can concatenate >> operations, €.g., cin >> numbert << nunber2 <<... The >> operator is also overloaded for the following pointer types: © const char *, const signed chan *, const unsigned char *: for inputting C- strings. it uses whitespace as delimiter and adds a terminating null character to the sting [TODO] Read "C-string input Flushing the Input Butfer - ignore() You can use the ignore() fo discard characters in the input buffer os ns 185 Notes 186 Notes ‘Object Oriented Programming wit C+ Unformatted Input/Output Functions pur(), get() and getline() The ostrean’s momber function put () can be used to pul out char. put() returns ‘the invoking ostream reference, and thus, can be cascaded. For example, as int, eturne EOF at end-of- invoking istrean [TODO] Example read(), write() and gcouni() ny; anand keep in char array it aces not append streamsize goount() const; 7/ Revura che numb put, instead of Console 10 Operations, Files Other Istream functions - peek() and putback() cher peek ( J/esvasns the next chara States of stream ‘The steam superclass ics_base maintains a data member to describe the states of the stream, which is @ bitmask of the type iostate. The flags are © eofbit: set whan an input operation reaches end of file © fai1bit: Tho last input operation failed to read the expected characters or output operation failed to write the expected characters, €9, getline) reads n characters without reaching delimiter character. © badbit: serious error due to failure of an IO operation (e.g file readiwnte error) or stream buffer. © goodbét: Absence of above error with value of O ‘These flags are defined as public static members in ios_base. They can be accessed directly Via ios base::failbit or via subclasses suchas. cin::failbit, ios::failbit. However, it 's more conveniance to use these public member functions of ios class © good(): returns true if goodbit is set (ie., no error. © eof():retuns true if eofbit is sot © fail(): retums true if Failbit or badbit is set © bad(): retums true if badbit is set clean(): clear eofbit, failbit and badbit Formatting Input/Output via Manipulators in and C++ provides a sot of manipulators to perform input and output formatting © Gomanip> header: setu(), setprecision(), setbas(), setfill(). © header: Fixed|scientific, left| right| internal, boolalphs|nob oolalpha, etc. Default Output Formatting The ostrean's << stream insertion operator is overloaded to convert @ numeric value {rom its internal representation (2.g., 16/32-bit int, 64-bit double) to the text form, 187 Notes 188 Notes ‘Object Oriented Programming wit C+ By default the values are displayed with a fleld.width just enough fo hold the text, without additional leading or trailing spaces. You need to provide spaces between the values, if desired © Forintegers, all digits willbe displayed, by detaut. For example, © coutec"[P<< 1<<"f =6) © cout <<" << 00001234567 << "<< endl) // |@.000123457| (Leading zones not counted touiands precision) © cout <<" << 0.00001234567 <<" <« endl, // |2.23457e-005] (scientific notation for e¢=-5) © bool values are displayed as 0 or 1 by default, instead of true or false s header) to set the field width © = setfill() manipulator (in header) to set the fill character © Loft| right |internai manipulator (in header) to set the text alignment Tho default field-width is 0, 1¢., just enough space to display the value. C++ never ‘runcetes data, and will expand the field to display the entire value ifthe fleld:width is 100 small. The setw() operation isnon-sticky. That is, itis applicable only to the next 1O operation, and reset back to 0 after the operation. The field.width property is applicable to both output and input operations Except setw(), all the other 10 manipulators are sticky, ie., they take effect until a now value is set Console 10 Operations, Files << "|" << endl; Example: Alignment tb << shows; // Ke I" xe samen) << 1)" header) to set the precision of floating-point number. © Fixed| scientific manipulators (in header) to set the floating-point display format. Floating point number can be display in 3 formatting modes: defauttfixadiscientific. ‘The precision is interpreted differently in default and non-defaurt modes (due to legacy). 189 Notes 190 Notes (Object Oriented Programmimg with C++ © Indefault mode (neither Fixed nor scientific used), a floating-point number is displayed in fixed-point notation (¢.g., 12.34) for exponent in the range of [-4, 5]; land scientific notation (e.g 1.281006) otherwise. The precision in default mode includes digits before and after the decimal point but exclude the leading zeros Fewer digits might be shown as the trailing zeros are not displayed. The defauit precision is 6. See the earlier examples for default mode with default precision of 6 As mentioned, the trailing zeros are not displayed in default mode, you can use manipulator shoupoint | noshowpoint to show or hide the trailing zeros. © In both Fixed (2.9, 12.34) and scientific (@.g., 1.2=+006), the precision sets the number of digits after decimel point. The default precision is also 6. For examples << << end: 56204006 after the fixed << setprecision nim ex 123.458789 << nym €e 123, x TIN << "I" << endls // 11231 You can also use ostrean’s member function precision(n) (eg. cout precision(n)) to set the floating-point precision, but precision() cannot be used with cout << operator. Console 10 Operations, Files Integral Number Base (dec|oct}hex, setbase) C++ support number bases (radixes) of decimal, hexadecimal and octal. You can use the following manipulators (defined in ios_base class, included in header) to manipulate the integral number base’ © hexdecloct: Set the integral number base. Negative hex and oct are displayed in 2s complement format. Altematively, you can use setbasa()10)16) (in header ). © showbaselnoshowbase: write hex values with Ox prefix: and octvalues with 0 pretix © showpos|noshowpos: write positive dec value with + sign uppercase|nouppercase: write uppercase in certain insertion operations, e.0., hex digits. It does not convert cheracters or strings to uppercasel These manipulators are sticky. For examples bool values (boolalpha|noboolalpha) © boolaiphalnoboclalpha’ read/write bool_-svalue—as._—alphabetic string true or false. J{ boolalpha - display bool as true/false cout << boolalpha << false <<"," << true << endl; // false, true cout << noboolalpha << false <<" "<< trua << endl, // 9,1 Other manipulators © skipwe[nesiépus. skip loading white spaces for certain input operations. © unitbuf|nounibuf flush output after each insertion operation, Notes © You need to include the header for setu(), setprecision() setfill(), and setbase() 191 Notes 192 Notes ‘Object Oriented Programming wit C+ * You can use ios_base’s (in header) member functions setf() and unset () to sat the individual formatting flags. However, they are not as user. friendly as using manipulators as discussed above. Furthermore, they cannot be used with cout << operator. File Input/Output (Header ) C++ handles file 10 similar to standard IO. In header , the class of stream is a Subclass of ostream, ifstrean is @ Subclass of istream and Fetream is a subclass of iostream for bi-directional 10. You need to include both and headers in your program for file 10. To wnte to a file, you construct a of steam object connecting to the output file, and use the ostream functions such as stream insertion <<, put() and write(). Similarly, to read from an input file, construct an i#stream object connecting to the input file, and use the istream functions such @s steam extraction >> get(), getline) and read() File IO requires an additional step to connect the file to the stream (ie, fle open) and disconnect from the stream (@,, file close), File Output The steps are © Construct an ostream object © Connect it to a file (Le., file open) and set the mode of file operation (e.g, truncate, append) Perform output operation via insertion >> operator or write(), put() functions Disconnect (close the file which flushes the output buffer) and free the ostream object, spent) By default, opening an output file creates a new file if the filename does not exist, or ‘runcatas it (clear its content) and starts wating as an empty file open(), close() and is_open() ioer:in | ios: ei at) For string ob: ct, “aeving Console 10 Operations, Files File Modes File modes are defined as static public member in i0s_base superclass. They can be referenced from ios baseor its subclasses - we typically use subclass ios. The available fle mode flags are: © 4os::4n-open fle for input operation © 40s: rout - open file for output operation © os: :app- output appends at the end of the file. © fos: :trune - truncate the file and discard old contents: © Jos: :binary - for binary (raw byte) |O operation, instead of character-based © Jos: rate - position the fle pointer "at the end’ for inputfoutput, © You can sat multiple flags via bitor (|) operator, eg. ios::out | ios::app to append output at the end of the fle, For output, the default is ios::out | ios::trunc. For input the default is ios File Input The steps are © Construct an istream object © Connect it to. fe (Le, fle open) and set the mode of fle operation. © Perform output operation via. extraction << operator or read(), get(), getline() functions © Disconnect (close the fils) and free the Sstrean object lenane, mode) > By default, opening an input fle 193 Notes 194 Notes (Objet Oriente Programming wth C++ Example on Simple File 1O I" Testing Simple File IO (TestSimpioFilelO cpp) */ 2. #include 3. include 4. include 5. include 6 using namespace st, 7. intmaing { 8. string flename = “est te 9. 11 Wite to File 10. ofstream foutfilename.c_str); // defauil mode is ios out | ios: trunc 11. if (fou) ¢ 12. comr << "error: open fle for output failed!” << endl, 13, abort(); 1! in header 14) 18, fout << “apple” << endl 16. fout << ‘orange” << endl 47. fout << "banana" << endl 18, fout close0), 19. Jf Read trom fle 20. ifstream finfilename.c_str); 1 detault mode ios:in 21. if fin) { 22. cert << "error: open file for input failed!" << endl 23. abort; 24.) 25. char ch, 26. while (fin.get(ch)) ¢ (til encLof fie 2T. cout <= ch; 2B) 29. finclosel) 30. return 0. 31.) Program Notes (¢ Most of the <#stream> functions (such as constructors, open()) supports flename in G-string only. You may need to extract the C-string from string object via the ¢_str() member function '* You could use is_open() to check ifthe file is opened successtuly. © The get(char_&) function returns @ null pointer (converted to false) when it reaches end.ot-fie Binary fle, read() and write() We need to use read() and write() member functions for binary fle (fle mode of dos: :binary), which readiwrite raw bytes without interpreting the bytes Console WO Operations, Files P* Testing Binary File |O (TestBinaryFilelO cpp) 7 2. include 3. #include 4. #include 5. #include 6 using namespace std; 7 intmain) { 8 9 siting flename Write to Fle 10. ofstream fouttfilename.c_st(), ios out | ios:binary) 14. if (out is_opent)) { test bi 12. cerr << "error: open file for output failed” << endl; 13. abort() 14} 16. inti= 1234 18. double d= 12.34 17. fout.wnte((char *)&i, sizeof(int)); 18. fout write((char *)&d, sizeof(double)), 49, fout closet) 20. Read from fe 21. ifstream fin(filename.c_str(), ios::in | ios::binary); 22. if tin is_open() { 23, cert << “error open file for input filed" << endl 24. abort() 25.4 26. int in 27. double din 28. fin.read((char *)&i_in, sizeof(int)); 29. cout << i_in << endl, 30. fin read((char *)&d_in, sizeof(double)), 31. cout <« din <= endl; 32. fin.close(); 33, return 0: Random Access File Random access fle is associated with a file pointer, which can be moved directly to any location in the file. Random access is crucial in certain applications such as databases and indexes. You can position the input pointer via seekg() and output pointer via seekp() Each of them has two versions. absolute and relative positioning 195 Notes 196 Notes ‘Object Oriented Programming wit C+ m & sookp (st: 2 seekp tellp (07 of output pointer Random access file is typically process as binary file, in both input and output modes [TODO] Example String Streams C++ provides a header, which uses the same public interface to support !O between a program and string object (butter) The sting steams is based on ostringstream (subclass of ostream), istringstream (subclass of istream) and bi-directional stringst ream (subclass of dostrean) > istringstrean, pasic_oete: ean ostringstroam: Stream input can be used to validate input data; stream output can be used to format the output ostringstream ostringstrean contents sout.str() << endle The ostringstream is responsible for dynamic memory allocation and management Console 10 Operations, Files Istringstream explicit istringstream (ios::openmode mode = 1os::n); // default with empty string istringstrean (con ing & buf, ios::openm: rtin)s // with initial evrin: neteuct Empat string 37 n >> iad oo sr KA KE KE KB KK endl, 8.5 Managing Output with Manipulators Manipulators are the most widely recognized approach to control output formatting and they take parameters in the if you use any manipulators that have parameters, the others are alteady included with +#include using namespace std, int main(){ const float tentt 4 const float one = 1.0; const float big = 1284567890 0, cout <<". * << tenth <<" " << one <<", " using namespace std; int main () { char stl] int val char ch =A’ cout width (5), cout << right cout << val <= endl return 0, } a) Steve jobs BA 199 Notes 200 Notes (Object Oriented Programming with O-+ c) 65 d) 65 What is the output of this program? #include using namespace std; intmain () a) b) °) 4) { inte, n= 43, cout << hex < using namespace std int main () 4 long pos, ofstream out outfile open (“test tt’), outtile. write (‘This is an apple",16); os = outfie tellin outile seekp (p05 - 7); outhie wnte (" sam”, 4); outils clos) retum0 } This is an apple apple sample This is a sample 7. What is the output of this program? #include using namespace std ‘Console YO Operations Files 201 int main () { Notes intn 77; cout width), cout <« iniesnel << n << endl return 0 1 a) 77 bd) 77 9-77 4) None of the mentioned 8. Whats the output ofthis program? #inelude #include locele> using namespace sid int main) { locale mylocale("), cout imbue( mylocale cout << (double) 3.14159 <« endl, return 0; y a) 314 b) 3.14159 ©) Error d)_ None of the mentioned 9. How many types of output stream classes are there in c++? a4 b) 2 3 a4 10. What must be specified when we construct an object of class ostream? a) stream b) streambut ©) memory 4d) None of the mentioned 202 Notes (Object Oriented Programmimg with C+ 8.8 Questions and Exercises Define C++ stream 2. What are C= stream classes? 3. What are unformatied 1/0 operations? 4. What are formatted 1/0 operations? 5. Write the difference between unformatted and formatted /O operations? 6. How does 1/0 operations are managed by manipulators 7 What is a stream? Describe briefly the features of Formatted and Unformatted |/O operations. 9. Why Unformatted I/O operations are used 7 410. What are manipulators? 8.9 Key Terms @ cin: Standard console input (keyboard). cout: Standard console output (screen) cpm: Standard printer (LPT1). cer: Standard error output (screen), clog: Standard log (screen). Check Your Progress: Answers: by 2 4) Allof the mentioned a) Writes to a fle d) 65 b) 2b d) This isa sample °) -17 b) 3.14150 0 3 0. b). streambut 8.10 Further Readings © Balagurusamy (2008) Object Oriented Programming with C++ Tata McGraw-Hill Education, © Subhash, K U. (2010) Object Oriented Programming With C++ Pearson Education India

You might also like