Download presentation
Presentation is loading. Please wait.
1
Input/Output Streams, Part 1
Department of Computer and Information Science, School of Science, IUPUI Input/Output Streams, Part 1 Dale Roberts, Lecturer Computer Science, IUPUI 7/23/2019
2
C++ Stream I/O One of the complex features of C++.
Many I/O features are object oriented. Type safe -- performed in a manner sensitive to the type of the data. Less error prone -- removes redundant type specifications. Extensible -- new user defined types can also be used in the same way as predefined types. Derivable -- these are real classes and hence can be derived and extended. 7/23/2019
3
Streams I/O occurs in streams of bytes – A stream is a sequence of bytes. The system I/O mechanisms are responsible for moving bytes from/to devices to/from memory in a consistent and a reliable manner. Provides "low level" and "high level" I/O capabilities. Low level - unformatted I/O - individual bytes – fast. High level - bytes grouped into meaningful units. 7/23/2019
4
Library: Header Files C++ iostream library provides hundreds of I/O capabilities. iostream.h -- interface to the stream library – contains basic information required for all I/O operations – contains cin, cout, cerr, clog objects. stream.h -- a subset provided as a compatibility to older stream libraries. iomanip.h -- for performing formatted I/O with parameterized stream manipulators. fstream.h -- user controlled file processing. strstream.h -- in-memory formatting of strings. stdiostream.h -- mix of C and C++ style I/O functions. 7/23/2019
5
iostream Library istream class (stream-input operations), ostream class (stream output oprations), iostream class (supports both stream I/O operations) ios class -> istream/ostream classes -> iostream class Operator overloading provides a convenient notation for performing I/O << (left shift operator) - stream output - “stream insertion operator” >> (right shift operator) - stream input - “stream extraction operator” << & >> are used with cin, cout, cerr, clog and user defined stream objects. cin - an object of istream class and is “tied” to the standard input device. cout - an object of ostream class and is “tied” to the standard output device. cerr - an object of ostream class and is “tied” to the standard error device. Output to cerr is unbuffered. clog - similar to cerr, but buffered. 7/23/2019
6
Stream Input cin (pronounced as see-in) is a replacement for scanf( ) function in C++. The cin statement sets the value of a variable to the value input from the keyboard. Skips all the white spaces and line breaks. Does not check for the type of the input – “smart”. Syntax: cin >> variable1 >> variable2 >> variable3.....; Cascading allowed -- >> associates from left to right and returns a reference to its left operand, i.e., cin Example: cin >> nNumber >> cChar; cin >> fWeight; cin >> fVolume >> sLength; 7/23/2019
7
Stream Output cout (pronounced as see-out) is the replacement for printf( ) in C++. Type safe and easy to use. Multiple statements can be chained together. Syntax: cout << var1 << " Some Text " << var2 << << endl; << associates from left to right – the overloaded << operator returns a reference to its left-operand, i.e., cout Example: cout << nNumber << " of students in a class scored " << nActualPts << " out of maximum " << nMaxPts << endl; cout << nNumber << " of students in a class scored " << nActualPts << " out of maximum " << nMaxPts << endl; 7/23/2019
8
iostream - Example #include<iostream.h> main() { int a, b cout << “Enter two numbers: ”; cin >> a >> b; cout << “a: " < a << “ b: ” << b << “;” << “ sum: ” << (a + b) << endl; } endl (end of line stream manipulator) -- achieves the effect of new line. It issues a new line character and also flushes the output buffer – cout << flush; >> operator skips white space characters (blanks, tabs, and new line) in the input stream. It returns false (0) if an EOF is encountered on the input stream. Parenthesis should be used (for the sake of clarity) whenever statements with multiple operators are used with << and >>. 7/23/2019
9
Output of char * Variables
C++ determines the data types automatically in the stream operations – sometimes this can cause problems. A character string is char * -- if we want to print the values of that pointer (i.e., the memory address of the first character of that string), but << operator has been overloaded to print data of type char * as a null-terminated string! => need to cast the pointer to (void *) to get the address. 7/23/2019
10
Character Output with “put”
The put() member function outputs one character cout.put (‘A’); cout.put(65); // ‘A’ = 65 (ASCII) Calls to put() can be overloaded cout.put(‘C’).put(‘S’).put(‘2’).put(‘6’).put(‘5’).put(‘\n’); The ‘.’ operator associates from left to right and the put() returns a reference to the object through which the put() call is invoked. 7/23/2019
11
Stream States Associated with every stream.
Appropriately set to handle error conditions. Might get set to any one of the following four values: eof - returns true if the stream has encountered an end-of-file. fail - returns true if an operation has been unsuccessful, such as, opening a file or a bad data type. bad - returns true if an invalid operation has been attempted. good - returns true if the operation is successful, or if none of the other states are true. 7/23/2019
12
Character Input The following functions are available for performing input operation with characters: cin.get(char); cin.get(char * array, streamsize n); //newline is terminator cin.get(char * array, streamsize n, char terminator); cin.getline(char *array, streamsize n); //newline is terminator cin.getline(char *array, streamsize n, char terminator); cin.ignore(streamsize n=1, int_type.t = Tr::eof()); cin.read(char *array, streamsize n); cin.peek(); cin.putback(); 7/23/2019
13
Character Input - cin.get()
cin.get(); // gets one charater (evenif it is whitespace) and returns this //character as the value of the function call -- returns EOF when //end-of-file is encountered. cin.get(ch); //inputs the next character from the istream (evenif white space) //and stores it in the argument – returns 0 with e-o-f. cin.get(ch * arr, streamsize n, ch delimiter = ‘\n’); //reads characters from the //input stream – reads up to 1 less than the size specified and terminates or //terminates when the delimiter is read – a \0 is inserted at the end. The //delimiter is not placed in the array and remains on the stream – the result of //a second consecutive get is an empty line unless the terminator is flushed //from the input stream. void fun() { char buf[100]; cin >> buf; //not safe, might overflow – also stops at a whitespace cin.get(buf, 100, ‘\n’); //Safe } 7/23/2019
14
Character Input - cin.getline()
Operates like a third version of the get(). It inserts a null character after the line in the character array. It removes the delimiter from the stream (reads and discards it) but does not store in the array. cin.getline(ch *arr, streamsize n, ch terminator = ‘\n’) void fun() { char buf[100]; while (cin.getline(buf, Max_Len, ‘\n’)) { …. } } 7/23/2019
15
Character Input – cin.ignore()
Skips over a designated number of characters (default is one character) or terminates upon encountering a designated delimiter (default is EOF which causes ignore() to skip the end of file when reading from a file). cin.ignore(streamsize n=1, int_type.t = Tr::eof()); void fun() { char buf[10]; cin >> buf; cin.ignore(Max_Len, ‘\n’); cout << buf; } 7/23/2019
16
cin.putback() and cin.peek()
cin.putback() places the previous character obtained by a get() on an input stream back onto that stream. Useful for applications that scan an input stream looking for a field beginning with a specific character. cin.peek() returns the next character from an input stream but does not remove that character from the stream. 7/23/2019
17
Unformatted I/O Unformatted I/O is performed with read() and write() functions. read() and write() – each of these inputs or outputs some number of bytes to or from a character array in memory. These bytes are not formatted in any way – these are “raw” bytes. 7/23/2019
18
read() cin.read(char *array, streamsize n);
void fun() { char buffer[100]; cin.read(buffer, 100); cout << buffer; } Reads n characters into buffer. Does not rely on the terminator and does not put ‘\0’ into the string. Simply put, does not make the string “C Style”. 7/23/2019
19
write() cout.out(char *array, streamsize n);
void fun() { char buffer[] = “CSCI 265”; cout.write(buffer, 5); cout << buffer; } Outputs first 5 characters from buffer (including the bull character that would cause output with cout and << to terminate). Simply put, does not make the string “C Style”. 7/23/2019
20
Character I/O - Example
#include <iostream> #include <String> main() { string in_string; //Write literal string to user's terminal cout << “Please enter your name: ”; //Read user's input to in_string cin >> in_string; if (in_string.empty()) { //Generate an error message to user's terminal cerr << "ERROR: input string is empty!" << endl;} else cout << “Hello!!, " << in_string << “!\n”; } 7/23/2019
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.