tailieunhanh - Lecture Programming in C++ - Chapter 4: Basic input and output

Lecture Programming in C++ - Chapter 4: Basic input and output. On completion of this chapter students will learned how to: Read input from keyboard, write output to file, read data from file, read and work with character data, work with the input buffer. | Chapter 4 – Basic Input and Output Reading Data Keyboard input cin object >> called extraction operator Syntax: cin >> variable; Example: Lesson cin >> income >> expense; Reads to values typed at keyboard (separated by whitespace) to memory locations names, income, and expense Prompt Message sent from program to screen Informs user what data to enter Precedes cin statement in program Lesson int age; cout > age; Input and Output Streams Series of bytes in sequence Flow from device to device Objects are regions of storage in memory Object used determines device stream comes from or goes to cin and cout are identifiers for objects defined by iostream (screen and keyboard) Lesson Writing Output to a File Similar to writing to screen Use object connected to output file Need the fstream header #include Open file for writing Declare object of ofstream class Lesson Opening Files General form ofstream object_name . | Chapter 4 – Basic Input and Output Reading Data Keyboard input cin object >> called extraction operator Syntax: cin >> variable; Example: Lesson cin >> income >> expense; Reads to values typed at keyboard (separated by whitespace) to memory locations names, income, and expense Prompt Message sent from program to screen Informs user what data to enter Precedes cin statement in program Lesson int age; cout > age; Input and Output Streams Series of bytes in sequence Flow from device to device Objects are regions of storage in memory Object used determines device stream comes from or goes to cin and cout are identifiers for objects defined by iostream (screen and keyboard) Lesson Writing Output to a File Similar to writing to screen Use object connected to output file Need the fstream header #include Open file for writing Declare object of ofstream class Lesson Opening Files General form ofstream object_name (“file_name”); Choose object_name like variable name object_name is object of class ofstream Filename is where output will be stored Can use full pathname “C:\\” Lesson Double quotes surround file_name Two backslashes needed – escape sequence for one Writing to Files General form object_name Declare object of ifstream ifstream object_name(“file_name”); Use ifstream object to read file like cin Lesson Reading From a File Use ifstream object to read file like cin used for keyboard ifstream infile(“C:\\”); infile >> salary1 >>

TỪ KHÓA LIÊN QUAN