Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— 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 2

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 3

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 4

5 Using cin and cout To use cin and cout, the preprocessor directive #include 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 5

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 6

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 7

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 8

9 9

10 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

11 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

12 Example 3-1 int a, b; double z; char ch, ch1, ch2; StatementInputValue Stored in Memory 1. cin >> ch;Ach = 'A‘ 2. cin >> ch;ABch = 'A', 'B' is held for later input 3. cin >> a;48a = 48 4. cin >> a;46.35a = 46,.35 is held for later input 5. cin >> z;74.35z = 74.35 6. cin >> z;39z = 39.0 7. cin >> z >> a;65.78 38z = 65.78, a = 38 12

13 StatementInputValue Stored in Memory 8. cin >> a >> b;4 60a = 4, b = 60 9. cin >> a >> ch >> z;57 A 26.9a = 57, ch = 'A', z = 26.9 10. cin >> a >> ch >> z;57 A26.9a = 57, ch = 'A', z = 26.9 11. cin >> a >> ch >> z;57 A26.9a = 57, ch = 'A', z = 26.9 12. cin >> a >> ch >> z;57A26.9a = 57, ch = 'A', z = 26.9 13. cin >> z >> ch >> a;36.78B34z = 36.78, ch = 'B', a = 34 14. cin >> z >> ch >> a;36.78B34z = 36.78, ch = 'B', a = 34 15. cin >> a >> b >> z;11 34a = 11, b = 34, computer waits for the next number 13

14 StatementInputValue Stored in Memory 16. cin >> a >> z;46 32.4 68a = 46, z = 32.4, 68 is held for later input 17. cin >> a >> z;78.49a = 78, z = 0.49 18. cin >> ch >> a; 256ch = '2', a = 56 19. cin >> a >> ch;256a = 256, computer waits for the input value for ch 20. cin >> ch1 >> ch2;A Bch1 = 'A', ch2 = 'B' 14

15 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

16 16 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 whitespace characters Another Way to Read char Data

17 17 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 firstmiddlelast At keyboard you type: A [ space]B [ space ] C [ Enter] firstmiddlelast ‘A’‘ ’‘B’

18 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

19 19 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

20 20

21 21

22 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 22

23 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 23

24 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 24

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

26 Disk I/O To use disk I/O Access #include 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

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

28 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

29 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

30 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 30

31 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(); 31

32 Run Time File Name Entry #include // Contains conversion function c_str ifstream inFile; 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

33 33 Algorithm Main ModuleLevel 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")

34 34 Get Name Get 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

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

36 36 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 //*************************************************************

37 37 #include // Access ofstream #include // 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

38 38 // 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; }


Download ppt "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."

Similar presentations


Ads by Google