1 / 38

Input/Output

Input/Output. Objectives. In this chapter you will: Learn what a stream is and examine input and output streams Explore how to use the input stream functions get , ignore , fill , putback , and peek Become familiar with file input and output Become familiar with input failure.

Download Presentation

Input/Output

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Input/Output

  2. Objectives In this chapter you will: • Learn what a stream is and examine input and output streams • Explore how to use the input stream functions get, ignore, fill, putback, and peek • Become familiar with file input and output • Become familiar with input failure

  3. Input/Output Streams • I/O: sequence of bytes (stream of bytes) from source to destination • Bytes are usually characters, unless program requires other types of information • Stream: sequence of characters from source to destination • Input Stream: sequence of characters from an input device to the computer • Output Stream: sequence of characters from the computer to an output device

  4. Standard I/O Devices • Use iostream to extract (receive) data from keyboard and send output to the screen • iostream contains definitions of two types • istream - input stream • ostream - output stream • iostream has two variables • cin - stands for common input • cout - stands for common output

  5. Using cin and cout • To use cin and cout, the preprocessor directive #include <iostream> must be used • The declaration is similar to the following C++ statements: istream cin; ostream cout; • Input stream variables: type istream • Output stream variables: type ostream

  6. cin and the Extraction Operator >> • The syntax of an input statement using cin and the extraction operator >> is cin >> variable >> variable...; • The extraction operator >> is binary • The left-hand operand is an input stream variable such as cin • The right-hand operand is a variable of a simple data type

  7. Standard Input • Every occurrence of >> extracts the next data item from the input stream • Two variables can be read using a single cin statement • No difference between a single cin with multiple variables and multiple cin statements with one variable • When scanning, >> skips all whitespace • Whitespace characters consist of blanks and certain nonprintable characters

  8. Data Type of Input • >> distinguishes between character 2 and number 2 by the right hand operand of >> • If it is of type char, the 2 is treated as character 2 • If it is of the type int (or double) the 2 is treated as the number 2

  9. Reading Data • When reading data into a char variable • Extraction operator >> skips leading whitespace, finds and stores only the next character • Reading stops after a single character

  10. Reading Data (Continued) • To read data into an int or double variable • Extraction operator >> skips leading whitespace, reads plus or minus sign (if any), reads the digits (including decimal) • Reading stops on whitespace non-digit character

  11. Example 3-1 int a, b; double z; charch, ch1, ch2; Statement Input Value Stored in Memory • cin>> ch;Ach = 'A‘ • cin>> ch;ABch = 'A', 'B' is held for later input • cin>> a;48a = 48 • cin>> a;46.35a = 46, .35is held for later input • cin>> z;74.35z = 74.35 • cin>> z;39z = 39.0 • cin>> z >> a;65.78 38z= 65.78, a = 38

  12. Statement Input Value Stored in Memory • cin>> a >> b; 4 60 a = 4, b = 60 • cin>> a >> ch >> z; 57 A 26.9 a = 57, ch = 'A', z = 26.9 • cin>> a >> ch >> z; 57 A26.9 a = 57, ch = 'A', z = 26.9 • cin>> a >> ch >> z; 57 A26.9 a = 57, ch = 'A', z = 26.9 • cin>> a >> ch >> z; 57A26.9 a = 57, ch = 'A', z = 26.9 • cin>> z >> ch >> a; 36.78B34 z = 36.78, ch = 'B', a = 34 • cin>> z >> ch >> a; 36.78 B34 z = 36.78, ch = 'B', a = 34 • cin>> a >> b >> z; 11 34 a = 11, b = 34, computer waits for the next number

  13. Statement Input Value Stored in Memory • cin>> a >> z; 46 32.4 68 a = 46, z = 32.4, 68 is held for later input • cin>> a >> z; 78.49 a = 78, z = 0.49 • cin>> ch >> a; 256 ch = '2', a = 56 • cin>> a >> ch; 256 a = 256, computer waits for the input value for ch • cin>> ch1 >> ch2; A B ch1 = 'A', ch2 = 'B'

  14. cin and the get Function • The get function • Inputs next character (including whitespace) • Stores character location indicated by its argument • The syntax of cin and the get function: cin.get(varChar); varChar • Is a char variable • Is the argument (parameter) of the function

  15. Another Way to Read char Data The get()function can be used to read a single character. get() obtains the very next character from the input stream without skipping any leading whitespacecharacters

  16. At keyboard you type:A[space]B[space]C[Enter] char first; char middle; char last; cin.get(first); cin.get(middle); cin.get(last); NOTE: The file reading marker is left pointing to the space after the ‘B’ in the input stream first middle last ‘A’ ‘ ’ ‘B’ first middle last

  17. cin and the ignore Function • ignore: discards a portion of the input • The syntax to use the function ignore is: cin.ignore(intExp, chExp); intExp is an integer expression chExp is a char expression • If intExp is a value m, the statement says to ignore the next m characters or all characters until the character specified by chExp

  18. Use function ignore() to skip characters The ignore()function is used to skip(read and discard) characters in the input stream The call cin.ignore(howMany, whatChar); will skip over up to howMany characters or until whatChar has been read, whichever comes first

  19. putback and peek Functions • putback function • Places previous character extracted by the get function from an input stream back to that stream • peek function • Returns next character from the input stream • Does not remove the character from that stream

  20. putback and peek Functions (continued) • The syntax for putback: • istreamVar.putback(ch); • istreamVar - an input stream variable, such as cin • ch is a char variable • The syntax for peek: • ch = istreamVar.peek(); • istreamVar is an input stream variable (cin) • ch is a char variable

  21. Dot Notation • In the statement cin.get(ch); cin and get are two separate identifiers separated by a dot • Dot separates the input stream variable name from the member, or function, name • In C++, dot is the member access operator

  22. input data output data disk file “myInfile.dat” disk file “myOut.dat” executing program your variable (of type ifstream) your variable (of type ofstream) Disk Files for I/O #include <fstream> 25

  23. Disk I/O To use disk I/O • Access #include <fstream> • Choose valid identifiers for your filestreams and declare them • Open the files and associate them with disk names • Use your filestream identifiers in your I/O statements(using >> and << , manipulators, get, ignore) • Close the files 26

  24. Disk I/O Statements #include <fstream> ifstream myInfile; // Declarations ofstream myOutfile; myInfile.open(“myIn.dat”); // Open files myOutfile.open(“myOut.dat”); myInfile.close(); // Close files myOutfile.close(); 27

  25. Opening a File Opening a file • Associates the C++ identifier for your file with the physical(disk) name for the file • If the input file does not exist on disk, open is not successful • If the output file does not exist on disk, a new file with that name is created • If the output file already exists, it is erased • Places a file reading marker at the very beginning of the file, pointing to the first character in the file 28

  26. Stream Fail State • When a stream enters the fail state, • Further I/O operations using that stream have no effect at all • The computer does not automatically halt the program or give any error message • Possible reasons for entering fail state include • Invalid input data (often the wrong type) • Opening an input file that doesn’t exist • Opening an output file on a disk that is already full or is write-protected 29

  27. Input Failure • Things can go wrong during execution • If input data does not match the corresponding variables, the program may run into problems • Trying to read a letter into an int or double variable would result in an input failure • If an error occurs when reading data • Input stream enters the fail state

  28. Input Failure (continued) • Once in a fail state, all further I/O statements using that stream are ignored • The program continues to execute with whatever values are stored in variables • This causes incorrect results • The clear function restores input stream to a working state istreamVar.clear();

  29. Run Time File Name Entry #include <string> // Contains conversion function c_str ifstreaminFile; string fileName; cout << “Enter input file name: “ << endl; // Prompt cin >> fileName; // Convert string fileName to a C string type inFile.open(fileName.c_str()); 32

  30. Algorithm Main Module Level 0 Open files Get social security number Get name Write data in proper formats Close files Open Files Level 1 inData.open("name.dat") outData.open("name.out")

  31. Get NameGet first name Get middle name or initial Get last name Write Data in Proper Formats Write first name, blank, middle name, blank, last name, blank, social security number Write last name, comma, first name, blank, middle name, blank, social security number Write last name, comma, blank, first name, blank, middle initial, period, blank, social security number Write first name, blank, middle initial, period, blank, last name

  32. Middle initial Level 2 Set initial to middleName.substr(0, 1) + period Close files inData.close() outData.close()

  33. C++ Program //************************************************************* // Format Names program // This program reads in a social security number, a first name // a middle name or initial, and a last name from file inData. // The name is written to file outData in three formats: // 1. First name, middle name, last name, and social security // number. // 2. last name, first name, middle name, and social // security number // 3. last name, first name, middle initial, and social // security number // 4. First name, middle initial, last name //*************************************************************

  34. #include <fstream> // Access ofstream #include <string> // Access string using namespace std; int main() { // Declare and open files ifstream inData; ofstream outData; inData.open("name.dat"); outData.open("name.out"); // Declare variables string socialNum; // Social security number string firstName; // First name string lastName; // Last name string middleName; // Middle name string initial; // Middle initial

  35. // Read in data from file inData inData >> socialNum >> firstName >> middleName >> lastName; // Access middle initial and append a period initial = middleName.substr(0, 1) + '.'; // Output information in required formats outData << firstName << ' ' << middleName << ' ' << lastName << ' ' << socialNum << endl; outData << lastName << ", " << firstName << ' ' << middleName << ' ' << socialNum << endl; outData << lastName << ", " << firstName << ' ' << initial << ' ' << socialNum << endl; outData << firstName << ' ' << initial << ' ' << lastName; // Close files inData.close(); outData.close(); return 0; }

More Related