Chapter 11 Customizing I/O Bjarne Stroustrup www.stroustup.com/Programming.

Slides:



Advertisements
Similar presentations
Chapter 10 Input/Output Streams
Advertisements

I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Chapter 16 Graphical User Interfaces
Chapter 3 Objects, types, and values Bjarne Stroustrup
Chapter 4 Computation Bjarne Stroustrup
Starting Out with C++, 3 rd Edition 1 Chapter 10 – Characters, Strings, and the string Class.
Database Chapters.
Chapter 10 Ch 1 – Introduction to Computers and Java Streams and File IO 1.
Chapter 8 Improving the User Interface
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 11 Customizing I/O Hartmut Kaiser
Chapter 3. Expressions and Interactivity CSC125 Introduction to C++
Sample Test 1 Question. A pattern of binary digits can be interpreted in several different ways. Show how the pattern translates using each of.
CS1061 C Programming Lecture 16: Formatted I/0 A. O’Riordan, 2004.
Programming Stream Manipulators. COMP102 Prog. Fundamentals I: Stream Manipulator Slide 2 Stream Manipulators in iostream.h Library I/O stream manipulators.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Decimal Addition What is going on? (carry) (subtract the base)
The printf Method The printf method is another way to format output. It is based on the printf function of the C language. System.out.printf(,,,..., );
Storing data Getting data out Data types Ruby as a foundation Program Variables Click icon to hear comments (the download may take a minute)
Simple Data Type Representation and conversion of numbers
CSCE 121: Introduction to Program Design and Concepts J. Michael Moore Fall 2014 Set 11: More Input and Output 1 Based on slides created by Bjarne.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
 Pearson Education, Inc. All rights reserved Formatted Output.
Chapter 3 COMPLETING THE BASICS Programming Fundamentals with C++1.
Chapter 11 Customizing I/O Bjarne Stroustrup
Supplemental Chapter Number Bases
Bit Manipulation when every bit counts. Questions on Bit Manipulation l what is the motivation for bit manipulation l what is the binary, hexadecimal,
Numbering System Base Conversion. Number systems Decimal – 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Binary – 0, 1 Octal – 0, 1, 2, 3, 4, 5, 6, 7 Hexadecimal system.
Number System. Number Systems Important Number systems – Decimal – Binary – Hexadecimal.
Definition Various stream manipulators can be used to specify the kinds of formatting to be performed during stream-I/O operations. Stream manipulators.
C++ Streams Lecture-2.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
C++ Streams Lecture-2. C++ Streams Stream  A transfer of information in the form of a sequence of bytes I/O Operations:  Input stream: A stream that.
C++ Lecture 1 Friday, 4 July History of C++ l Built on top of C l C was developed in early 70s from B and BCPL l Object oriented programming paradigm.
1 Simple Input/Output  C++ offers the iostream library, which defines a system of character-oriented Input/Output (I/O) using object oriented programming.
Programming Fundamentals with C++1 Chapter 3 COMPLETING THE BASICS.
1 COMS 261 Computer Science I Title: Functions Date: October 24, 2005 Lecture Number: 22.
1 Manipulators manipulators are used only in input and output statements endl, fixed, showpoint, setw, and setprecision are manipulators that can be used.
Values, Types, and Variables. Values Data Information Numbers Text Pretty much anything.
Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.
CSCI-1411 F UNDAMENTALS O F C OMPUTING L AB Shane Transue Summer
Week 7 : String and photo processing. Today’s Tasks  Practice list and string  Convert Decimal to any radix base number  Between Binary and Hexadecimal.
Arithmetic Chapter 4 Subject: Digital System Year: 2009.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the differences between text and binary files ❏ To write programs.
28 Formatted Output.
Topic: Binary Encoding – Part 1
Chapter 11 Customizing I/O
Standard Input - Output
TMF1414 Introduction to Programming
Chapter 11 Customizing I/O
Binary Quiz UIN: ____________________
Programming in Perl Introduction
“The fastest I/O is no I/O.” Nils-Peter Nelson, Bell Labs
Lecture 13 Input/Output Files.
C++ fundamentals Lecture 1, Chapter 2 – pp /22/2018 Y K Choi.
IO Overview CSCE 121 J. Michael Moore
Manipulators CSCE 121 J. Michael Moore
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Introduction to Primitive Data types
There are 10 types of people of people in this world…
Formatting the Output The C++ standard library supplies many manipulators: endl, setw, fixed, showpoint, setprecesion. If we want to use endl, fixed, or.
Chapter 3: Expressions and Interactivity
Chapter 11 Customizing I/O
Storing Integers and Fractions
Chapter 11 Customizing I/O
Remember the 10 types of people of people in this world…
Computer Science 1 Review and finish Number base conversion
IO Overview CSCE 121 Strongly influenced by slides created by Bjarne Stroustrup and Jennifer Welch.
Introduction to Primitive Data types
Presentation transcript:

Chapter 11 Customizing I/O Bjarne Stroustrup

Overview Input and output Input and output Numeric output Numeric output Integer Integer Floating point Floating point File modes File modes Binary I/O Binary I/O Positioning Positioning String streams String streams Line-oriented input Line-oriented input Character input Character input Character classification Character classification 2Stroustrup/Programming

Kinds of I/O Individual values Individual values See Chapter 4, 10 See Chapter 4, 10 Streams Streams See Chapters See Chapters Graphics and GUI Graphics and GUI See Chapters See Chapters Text Text Type driven, formatted Type driven, formatted Line oriented Line oriented Individual characters Individual characters Numeric Numeric Integer Integer Floating point Floating point User-defined types User-defined types 3Stroustrup/Programming

Observation As programmers we prefer regularity and simplicity As programmers we prefer regularity and simplicity But, our job is to meet peoples expectations But, our job is to meet peoples expectations People are very fussy/particular/picky about the way their output looks People are very fussy/particular/picky about the way their output looks They often have good reasons to be They often have good reasons to be Convention/tradition rules Convention/tradition rules What does 123,456 mean? What does 123,456 mean? What does (123) mean? What does (123) mean? The world (of output formats) is weirder than you could possibly imagine The world (of output formats) is weirder than you could possibly imagine 4Stroustrup/Programming

Output formats Integer values Integer values 1234(decimal) 1234(decimal) 2322(octal) 2322(octal) 4d2(hexadecimal) 4d2(hexadecimal) Floating point values Floating point values (general) (general) e+03(scientific) e+03(scientific) (fixed) (fixed) Precision (for floating-point values) Precision (for floating-point values) (precision 6) (precision 6) (precision 5) (precision 5) Fields Fields |12|(default for | followed by 12 followed by |) |12|(default for | followed by 12 followed by |) | 12|(12 in a field of 4 characters) | 12|(12 in a field of 4 characters) 5Stroustrup/Programming

Numerical Base Output You can change base You can change base Base 10 == decimal; digits: Base 10 == decimal; digits: Base 8 == octal; digits: Base 8 == octal; digits: Base 16 == hexadecimal; digits: a b c d e f Base 16 == hexadecimal; digits: a b c d e f // simple test: cout << dec << 1234 << "\t(decimal)\n" << hex << 1234 << "\t(hexadecimal)\n" << oct << 1234 << "\t(octal)\n"; // The '\t' character is tab (short for tabulation character) // results: 1234(decimal) 4d2(hexadecimal) 2322(octal) 6Stroustrup/Programming

Sticky Manipulators You can change base You can change base Base 10 == decimal; digits: Base 10 == decimal; digits: Base 8 == octal; digits: Base 8 == octal; digits: Base 16 == hexadecimal; digits: a b c d e f Base 16 == hexadecimal; digits: a b c d e f // simple test: cout << 1234 << '\t' << hex << 1234 << '\t' << oct << 1234 << '\n'; cout << 1234 << '\n';// the octal base is still in effect // results: 12344d Stroustrup/Programming

Other Manipulators You can change base You can change base Base 10 == decimal; digits: Base 10 == decimal; digits: Base 8 == octal; digits: Base 8 == octal; digits: Base 16 == hexadecimal; digits: a b c d e f Base 16 == hexadecimal; digits: a b c d e f // simple test: cout << 1234 << '\t' << hex << 1234 << '\t' << oct << 1234 << endl;// '\n' cout << showbase << dec;// show bases cout << 1234 << '\t' << hex << 1234 << '\t' << oct << 1234 << '\n'; // results: 12344d x4d Stroustrup/Programming

Floating-point Manipulators You can change floating-point output format You can change floating-point output format general – iostream chooses best format using n digits (this is the default) general – iostream chooses best format using n digits (this is the default) scientific – one digit before the decimal point plus exponent; n digits after. scientific – one digit before the decimal point plus exponent; n digits after. fixed – no exponent; n digits after the decimal point fixed – no exponent; n digits after the decimal point // simple test: cout << << "\t\t(general)\n"// \t\t to line up columns << fixed << << "\t(fixed)\n" << fixed << << "\t(fixed)\n" << scientific << << "\t(scientific)\n"; << scientific << << "\t(scientific)\n"; // results: (general) (fixed) e+003(scientific) 9Stroustrup/Programming

Precision Manipulator Precision (the default is 6) Precision (the default is 6) general – precision is the number of digits general – precision is the number of digits Note: the general manipulator is not standard, just in std_lib_facilities.h Note: the general manipulator is not standard, just in std_lib_facilities.h scientific – precision is the number of digits after the. (dot) scientific – precision is the number of digits after the. (dot) fixed – precision is the number of digits after the. (dot) fixed – precision is the number of digits after the. (dot) // example: cout << << '\t' << fixed << << '\t' << scientific << << '\n'; cout << general << setprecision(5) << << '\t' << fixed << << '\t' << scientific << << '\n'; cout << general << setprecision(8) << << '\t' << fixed << << '\t' << scientific << << '\n'; // results (note the rounding): e e e Stroustrup/Programming

Output field width A width is the number of characters to be used for the next output operation A width is the number of characters to be used for the next output operation Beware: width applies to next output only (it doesnt stick like precision, base, and floating-point format) Beware: width applies to next output only (it doesnt stick like precision, base, and floating-point format) Beware: output is never truncated to fit into field Beware: output is never truncated to fit into field (better a bad format than a bad value) (better a bad format than a bad value) // example: cout << <<'|'<< setw(4) << << '|' << setw(8) << << '|' << << "|\n"; cout << <<'|'<< setw(4) << << '|' << setw(8) << << '|' << << "|\n"; cout << "asdfgh" <<'|'<< setw(4) << "asdfgh" << '|' << setw(8) << "asdfgh" << '|' << "asdfgh" << "|\n"; // results: |123456| |123456| | | | | asdfgh|asdfgh| asdfgh|asdfgh| 11Stroustrup/Programming

Observation This kind of detail is what you need textbooks, manuals, references, online support, etc. for This kind of detail is what you need textbooks, manuals, references, online support, etc. for You always forget some of the details when you need them You always forget some of the details when you need them 12Stroustrup/Programming

A file At the fundamental level, a file is a sequence of bytes numbered from 0 upwards At the fundamental level, a file is a sequence of bytes numbered from 0 upwards Other notions can be supplied by programs that interpret a file format Other notions can be supplied by programs that interpret a file format For example, the 6 bytes "123.45" might be interpreted as the floating-point number For example, the 6 bytes "123.45" might be interpreted as the floating-point number :1:2: Stroustrup/Programming

File open modes By default, an ifstream opens its file for reading By default, an ifstream opens its file for reading By default, an ofstream opens its file for writing. By default, an ofstream opens its file for writing. Alternatives: Alternatives: ios_base::app // append (i.e., add to the end of the file) ios_base::app // append (i.e., add to the end of the file) ios_base::ate // at end (open and seek to end) ios_base::ate // at end (open and seek to end) ios_base::binary // binary mode – beware of system specific behavior ios_base::binary // binary mode – beware of system specific behavior ios_base::in // for reading ios_base::in // for reading ios_base::out // for writing ios_base::out // for writing ios_base::trunc // truncate file to 0-length ios_base::trunc // truncate file to 0-length A file mode is optionally specified after the name of the file: A file mode is optionally specified after the name of the file: ofstream of1(name1);// defaults to ios_base::out ofstream of1(name1);// defaults to ios_base::out ifstream if1(name2);// defaults to ios_base::in ifstream if1(name2);// defaults to ios_base::in ofstream ofs(name, ios_base::app); // append rather than overwrite ofstream ofs(name, ios_base::app); // append rather than overwrite fstream fs("myfile", ios_base::in|ios_base::out); // both in and out fstream fs("myfile", ios_base::in|ios_base::out); // both in and out 14Stroustrup/Programming

Text vs. binary files In binary files, we use sizes to delimit values In text files, we use separation/termination characters ????? 12345??? as characters : as characters: as binary: 123 as binary : ? as characters: Stroustrup/Programming

Text vs. binary Use text when you can Use text when you can You can read it (without a fancy program) You can read it (without a fancy program) You can debug your programs more easily You can debug your programs more easily Text is portable across different systems Text is portable across different systems Most information can be represented reasonably as text Most information can be represented reasonably as text Use binary when you must Use binary when you must E.g. image files, sound files E.g. image files, sound files 16Stroustrup/Programming

Binary files int main() // use binary input and output { cout << "Please enter input file name\n"; string name; cin >> name; ifstream ifs(name.c_str(),ios_base::binary);// note: binary if (!ifs) error("can't open input file ", name); cout << "Please enter output file name\n"; cin >> name; ofstream ofs(name.c_str(),ios_base::binary);// note: binary if (!ofs) error("can't open output file ",name); // binary tells the stream not to try anything clever with the bytes 17Stroustrup/Programming

Binary files vector v; // read from binary file: int i; while (ifs.read(as_bytes(i),sizeof(int)))// note: reading bytes v.push_back(i); // … do something with v … // write to binary file: for(int i=0; i<v.size(); ++i) ofs.write(as_bytes(v[i]),sizeof(int));// note: writing bytes return 0; } // for now, treat as_bytes() as a primitive 18Stroustrup/Programming

Positioning in a filestream fstream fs(name.c_str());// open for input and output // … fs.seekg(5);// move reading position (g for get) to 5 (the 6 th character) char ch; fs>>ch;// read and increment reading position cout << "character[6] is " << ch << '(' << int(ch) << ")\n"; fs.seekp(1);// move writing position (p for put) to 1 (the 2 nd character) fs<<'y';// write and increment writing position 19 … y A file: 2 6 Put position: Get position: 0:1: Stroustrup/Programming

Positioning Whenever you can Whenever you can Use simple streaming Use simple streaming Streams/streaming is a very powerful metaphor Streams/streaming is a very powerful metaphor Write most of your code in terms of plain istream and ostream Write most of your code in terms of plain istream and ostream Positioning is far more error-prone Positioning is far more error-prone Handling of the end of file position is system dependent and basically unchecked Handling of the end of file position is system dependent and basically unchecked 20Stroustrup/Programming

String streams A stringstream reads/writes from/to a string rather than a file or a keyboard/screen double str_to_double(string s) // if possible, convert characters in s to floating-point value { istringstream is(s);// make a stream so that we can read from s double d; is >> d; if (!is) error("double format error"); return d; } double d1 = str_to_double("12.4");// testing double d2 = str_to_double("1.34e-3"); double d3 = str_to_double("twelve point three");// will call error() 21Stroustrup/Programming

String streams Very useful for Very useful for formatting into a fixed-sized space (think GUI) formatting into a fixed-sized space (think GUI) for extracting typed objects out of a string for extracting typed objects out of a string 22Stroustrup/Programming

Type vs. line Read a string Read a string string name; cin >> name;// input: Dennis Ritchie cout << name << '\n';// output: Dennis Read a line Read a line string name; getline(cin,name);// input: Dennis Ritchie cout << name << '\n';// output: Dennis Ritchie // now what? // maybe: istringstream ss(name); ss>>first_name;ss>>second_name; 23Stroustrup/Programming

Characters You can also read individual characters You can also read individual characters char ch; while (cin>>ch) {// read into ch, skipping whitespace characters if (isalpha(ch)) { // do something }} while (cin.get(ch)) {// read into ch, dont skip whitespace characters if (isspace(ch)) { if (isspace(ch)) { // do something } else if (isalpha(ch)) { // do something else }} 24Stroustrup/Programming

Character classification functions If you use character input, you often need one or more of these (from header ): If you use character input, you often need one or more of these (from header ): isspace(c)// is c whitespace? (' ', '\t', '\n', etc.) isspace(c)// is c whitespace? (' ', '\t', '\n', etc.) isalpha(c)// is c a letter? ('a'..'z', 'A'..'Z') note: not '_' isalpha(c)// is c a letter? ('a'..'z', 'A'..'Z') note: not '_' isdigit(c)// is c a decimal digit? ('0'.. '9') isdigit(c)// is c a decimal digit? ('0'.. '9') isupper(c)// is c an upper case letter? isupper(c)// is c an upper case letter? islower(c)// is c a lower case letter? islower(c)// is c a lower case letter? isalnum(c)// is c a letter or a decimal digit? isalnum(c)// is c a letter or a decimal digit? 25Stroustrup/Programming

Line-oriented input Prefer >> to getline() Prefer >> to getline() i.e. avoid line-oriented input when you can i.e. avoid line-oriented input when you can People often use getline() because they see no alternative People often use getline() because they see no alternative But it often gets messy But it often gets messy When trying to use getline(), you often end up When trying to use getline(), you often end up using >> to parse the line from a stringstream using >> to parse the line from a stringstream using get() to read individual characters using get() to read individual characters 26Stroustrup/Programming

Next lecture Graphical output Graphical output Creating a window Creating a window Drawing graphs Drawing graphs 27Stroustrup/Programming