More on File I/O Strings in C++ CS 16: Solving Problems with Computers I Lecture #10

Similar documents
File I/O and String Manipula3ons CS 16: Solving Problems with Computers I Lecture #11

Introduc)on to Arrays in C++ Review for Midterm #2 CS 16: Solving Problems with Computers I Lecture #12

File I/O CS 16: Solving Problems with Computers I Lecture #9

More on Strings in C++ Arrays CS 16: Solving Problems with Computers I Lecture #11

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Simple File I/O.

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

What we will learn about this week:

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Chapter 12. Streams and File I/O

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5

Week 3: File I/O and Formatting 3.7 Formatting Output

Lecture 3 The character, string data Types Files

CPE Summer 2015 Exam I (150 pts) June 18, 2015

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

File Input/Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #10

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

what are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8

Numerical Conversions Intro to Strings in C/C++ CS 16: Solving Problems with Computers I Lecture #8

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

I/O Streams and Standard I/O Devices (cont d.)

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Arrays 2 CS 16: Solving Problems with Computers I Lecture #12

CS11 Advanced C++ Lecture 2 Fall

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

Programming in C/C

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

More File Operations. Lecture 17 COP 3014 Spring april 18, 2018

Chapter 9. Strings. 國立雲林科技大學資訊工程研究所張傳育 (Chuan Yu Chang ) 博士

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Func%ons in C++ Part 2 CS 16: Solving Problems with Computers I Lecture #5

Definition Matching (10 Points)

Engineering Problem Solving with C++, Etter

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Advanced Flow Control CS 16: Solving Problems with Computers I Lecture #5

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

Pre- Defined Func-ons in C++ Review for Midterm #1

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Chapter 14 Sequential Access Files

std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

Programming in C/C

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Exercises with Linked Lists CS 16: Solving Problems with Computers I Lecture #15

(More) Fun with Pointers and Linked Lists! CS 16: Solving Problems with Computers I Lecture #17

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance

CS 103 Unit 14 - Streams

Ch 6-8. C-Strings. April 30, Prof. Young-Tak Kim

Chapter 3 - Notes Input/Output

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York

Flow Control in C++ Condi&onals & Loops CS 16: Solving Problems with Computers I Lecture #4

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

C++ Input/Output Chapter 4 Topics

Functions and the MIPS Calling Convention 2 CS 64: Computer Organization and Design Logic Lecture #11

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

ENGI 1020 Introduction to Computer Programming R E Z A S H A H I D I J U L Y 2 6,

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

CSCE 110 PROGRAMMING FUNDAMENTALS

Programming in C/C

Unit 14. Passing Arrays & C++ Strings

Strings in Python 1 Midterm#1 Exam Review CS 8: Introduction to Computer Science Lecture #6

UEE1302 (1102) F10: Introduction to Computers and Programming

Welcome to Solving Problems with Computers I

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

STL. Prof Tejada Week 14

CS2141 Software Development using C/C++ Stream I/O

Linked Lists CS 16: Solving Problems with Computers I Lecture #16

Function Calling Conventions 2 CS 64: Computer Organization and Design Logic Lecture #10

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Chapter 10 Characters, Strings, and the string class

Introduc)on to C++ CS 16: Solving Problems with Computers I Lecture #2

Streams. Rupesh Nasre.

CS 103 Unit 14 - Streams

CS242 COMPUTER PROGRAMMING

In this chapter, you will learn about: An Array Type for Strings. The Standard string Class. Vectors. Introduction Computer Science 1 CS 23021

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

CS31 Discussion 1E. Jie(Jay) Wang Week5 Oct.27

CS 241 Computer Programming. Introduction. Teacher Assistant. Hadeel Al-Ateeq

2 nd Week Lecture Notes

Name Section: M/W T/TH Number Definition Matching (8 Points)

Topic 2. Big C++ by Cay Horstmann Copyright 2018 by John Wiley & Sons. All rights reserved

Transcription:

More on File I/O Strings in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB

Announcements Heads- Up: Midterm #2 is on Tuesday 11/14 Found evidence that students are COPYING from each other. That s a bad thing It s Qme to remind everyone of the plagiarism policy (Students: read the syllabus, if you forgot it!! Also read the UCSB webpage on Academic Integrity hvp://judicialaffairs.sa.ucsb.edu/academicintegrity.aspx ) 11/2/17 Matni, CS16, Fa17 2

STUDENT X ß 96% Match! à STUDENT Y StarPng with Lab 5, we will be taking a close look at ALL student lab exercise submissions and checking for cheapng/copying from one another or from an internet source. You will get a ZERO, if caught, and be reported, per the plagiarism policy.

Lecture Outline More on File I/O (Ch. 6) File I/O Use in FuncQons End of File DetecQon Using get, getline, put, putback More on Strings (Ch. 8.1, 8.2) More manipulators! Built- in string funcqons 11/2/17 Matni, CS16, Fa17 4

#include <fstream> int main() { ifstream LovelyInput; ofstream AwesomeOutput; LovelyInput.open( ThatInputFile.txt ); if (LovelyInput.fail()) { cerr << Bad Mojo!\n ; exit(1); } LovelyInput >> MyVar1; LovelyInput >> MyVar2; LovelyInput.close(); AwesomeOutput.open( OutWithIt.txt ); AwesomeOutput << Dodgers :( \n ; AwesomeOutput << 521; AwesomeOutput << sqrt(521); AwesomeOutput.close(); 11/2/17 Matni, CS16, Fa17 5

Let s Look at a Demo RWDemo.cpp Found in your demo folder under demo_lect9 11/2/17 Matni, CS16, Fa17 6

Can I Call a FuncQon to do File I/O? Yes! But there are strict rules about it: Mainly: stream objects must be passed by reference into funcqons 11/2/17 Matni, CS16, Fa17 7

Stream Names as Arguments Streams can be arguments to a funcqon The funcqon's formal parameter for the stream must be call- by- reference Example: void make_neat(ifstream& messy_file, ofstream& neat_file); 11/2/17 Matni, CS16, Sp17 8

DetecQng the End of a File Input files used by a program may vary in length Programs may not be able to correctly assume the number of items or lines in the file You may not know either! C++ provides 2 methods that can tell you if you have reached the end of a file that you are reading 11/2/17 Matni, CS16, Sp17 9

DetecQng the End of a File The Boolean expression (in_stream.eof( )) UQlizes the member funcqon eof() or end- of- file True if you have reached the end of file False if you have not reached the end of file The Boolean expression (in_stream >> next) Does 2 things: * Reads a value from in_stream and stores it in variable next * Returns a Boolean value True if a value can be read and stored in next False if there is not a value to be read (i.e. b/c of the end of the file) 11/2/17 Matni, CS16, Sp17 10

End of File Example using while (ifstream >> next) method To calculate the average of the numbers in a file that contains numbers of type double: ifstream in_stream; in_stream.open( inputfile.txt ) double next, sum(0), average; int count = 0; while(in_stream >> next) { sum = sum + next; count++; } average = sum / count; 11/2/17 Matni, CS16, Sp17 11

End of File Example using while (!ifstrem.eof() ) method To read each character in a file, and then write it to the screen: More on.get() later in_stream.get(next); while (! in_stream.eof( ) ) { cout << next; in_stream.get(next); } 11/2/17 Matni, CS16, Sp17 12

In general: Which of the 2 Should I Use?! Use eof when input is treated as text and using a member funcqon get to read input See demo file: changectocpp.cpp Use the extracpon operator (>>) method when processing numerical data 11/2/17 Matni, CS16, Sp17 13

Member FuncQon get(char) Member funcqon of every input stream i.e. it works for cin and for ifstream Reads one character from an input stream Stores the character read in a variable of type char, which is the single argument the funcqon takes Does not use the extracqon operator (>>) Does not skip whitespaces, like blanks, tabs, new lines Because these are characters too! 11/2/17 Matni, CS16, Sp17 14

Using get These lines use get to read a character and store it in the variable next_symbol char next_symbol; cin.get(next_symbol); Any character will be read with these statements Blank spaces too! \n too! (The newline character) \t too! (The tab character) 11/2/17 Matni, CS16, Sp17 15

get Syntax See demo file: get_example.cpp input_stream_object.get(char_variable); Examples: char next_symbol; cin.get(next_symbol); ifstream in_stream; in_stream.open("infile.txt"); in_stream.get(next_symbol); 11/2/17 Matni, CS16, Sp17 16

More About get Given this code: char c1, c2, c3; cin.get(c1); cin.get(c2); cin.get(c3); and this input: AB CD Results: in c1 = 'A' c2 = 'B' c3 = '\n' On the other hand: cin >> c1 >> c2 >> c3; would place 'C' in c3 because ">>" operator skips newline characters 11/2/17 Matni, CS16, Sp17 17

The End of The Line using get To read and echo an enqre line of input by collecqng all characters before the newline character Look for '\n' at the end of the input line: cout <<"Enter a line of input and I will echo it.\n"; char symbol; do { cin.get(symbol); cout << symbol; } while (symbol!= '\n'); All characters, including '\n' will be output 11/2/17 Matni, CS16, Sp17 18

NOTE: '\n ' vs "\n " '\n' A value of type char Can be stored in a variable of type char "\n" A string containing only one character Cannot be stored in a variable of type char In a cout statement they produce the same result 11/2/17 Matni, CS16, Sp17 19

getline funcqon See demo file: getline_example.cpp For standard inputs, cin is fine: but it ignores space, tabs, and newlines SomeQmes, you want to get the en<re line of data! Best to use the funcqon getline for that purpose. You have to include the <iostream> library (which you likely already do!) Popular Usage: getline(ifstream_object, string); getline(cin, string); 11/2/17 Matni, CS16, Sp17 20

Member FuncQon put Member funcqon for ofstream Requires one argument of type char Places its argument of type char in the output stream Not very popular 11/2/17 Matni, CS16, Sp17 21

put Syntax output_stream_object.put(char_variable); Examples: ofstream out_stream; out_stream.open("outfile.dat"); out_stream.put('z'); 11/2/17 Matni, CS16, Sp17 22

Member FuncQon putback The putback member funcqon puts a char in the input stream putback is a member funcqon of every input stream cin, ifstream Useful if you want to assess a character and decide what to do from there (but spll want to re- use that character) Character placed in the stream does not have to be a character read from the stream! 11/2/17 Matni, CS16, Sp17 23

putback Example Also see demo file: putback_example.cpp The following code reads up to the first blank in the input stream fin, and writes the characters to the file connected to the output stream fout fin.get(next); while (next!= ' ') { fout.put(next); fin.get(next); } fin.putback(next); The blank space read to end the loop is put back into the input stream 11/2/17 Matni, CS16, Sp17 24

Character FuncQons Several predefined funcqons exist to facilitate working with characters The cctype library is required for most of them #include <cctype> using namespace std; 11/2/17 Matni, CS16, Sp17 25

The toupper FuncQon toupper returns the argument's upper case character toupper('a') returns 'A' toupper('a') returns 'A' DOES NOT WORK WITH STRINGS! IT S FOR CHARACTERS ONLY! 11/2/17 Matni, CS16, Sp17 26

The tolower FuncQon Similar to toupper funcqon tolower returns the argument's lower case character tolower('a') returns 'a' tolower('a') returns 'a' 11/2/17 Matni, CS16, Sp17 27

The isspace FuncQon isspace returns true if the argument is whitespace Whitespace is: spaces, tabs, and newlines So, isspace(' ') returns true, so does isspace( \n ) Example: if (isspace(next) ) cout << '- '; else cout << next; Prints a '- ' if next contains a space, tab, or newline character 11/2/17 Matni, CS16, Sp17 28

11/2/17 29

String Basics Use the + operator to concatenate 2 strings string str1 = Hello, str2 = world!, str3; str3 = str1 + str2; // str3 will be Hello world! Use the += operator to append to a string str1 += Z ; // str1 will be Hello Z Call out a character in the string based on posipon, using [ ] braces Recall array indices in C++ start at zero (0) cout << str1[0]; // prints out H cout << str2[3]; // prints out l 11/2/17 Matni, CS16, Sp17 30

Character Manipulators Work Too! Include <cctype> to use with, for example, toupper() string s = hello ; s[0] = toupper(s[0]); cout << s; // Will display Hello or to use with tolower() string s = HELLO ; for (int i=0; i < 5; i++) s[i] = tolower(s[i]); cout << s; // Will display hello 11/2/17 Matni, CS16, Sp17 31

Built- In String Member FuncQons Search funcqons find, rfind, find_first_of, find_first_not_of Descriptor funcqons length, size Content changers substr, replace, append, insert, erase 11/2/17 Matni, CS16, Sp17 32

Search FuncQons: find 1 You can search for a the first occurrence of a string in a string with the.find funcqon [7] string str = With a banjo on my knee and ban the bomb- ban! ; int position = str.find( ban ); cout << position; // Will display the number 7 11/2/17 Matni, CS16, Sp17 33

Search FuncQons: find 2 You can also search for a the first occurrence of a string in a string, starqng at posiqon n, using a slight mod to.find() [28]? string str = With a banjo on my knee and ban the bomb- ban! ; int position = str.find( ban, 12); cout << position; // Will display the number 28 11/2/17 Matni, CS16, Sp17 34

Search FuncQons: find 3 You can use the find funcqon to make sure a substring is NOT in the target string using the no posiqon value string::npos is returned if no posiqon exists if (MyStr.find("piano") == string::npos) cout << "There is no piano there! // This will happen if piano is NOT in the string MyStr 11/2/17 Matni, CS16, Sp17 35

Search FuncQons: rfind You can search for a the last occurrence of a string in a string with the.rfind funcqon [41] string str = With a banjo on my knee and ban the bomb- ban! ; int rposition = str.rfind( ban ); cout << rposition; // Will display the number 41 11/2/17 Matni, CS16, Sp17 36

Search FuncQons: find_first(_not)_of find_first_of Finds 1 st occurrence of any of the characters included in the specified string find_first_not_of Finds 1 st occurrence of a character that is not any of the characters included in the specified string Example: See demo file: non_numbers.cpp 11/2/17 Matni, CS16, Sp17 37

Descriptor FuncQons: length and size The length funcqon returns the length of the string The member funcqon size is the same exact thing So, if string str1 = Mama Mia!, then str1.length() = 9 and str1.size() = 9 also Example what will this code do?: string name = Bubba Smith ; for (int i = name.length(); i > 0; i- - ) cout << name[i- 1]; 11/2/17 Matni, CS16, Sp17 38

Content Changers: append Use funcqon append to append one string to another string name1 = Max ; string name2 = Powers ; cout << name1.append(name2); // Displays Max Powers Does the same thing as: name1 + name2 11/2/17 Matni, CS16, Sp17 39

Content Changers: erase Use funcqon erase to clear a string to an empty string One use is: name1.erase() - - Does the same thing as: name1 = Another use is: name1.erase(start posi:on, how many chars to erase) Erases only part of the string Example: string s = Hello! ; cout << s.erase(2, 2); // Displays Heo! 11/2/17 Matni, CS16, Sp17 40

Content Changers: replace and insert Use funcqon replace to replace part of a string with another Popular Usage: string.replace(start posi:on, # of places aber start posi:on to replace, replacement string) Use funcqon insert to insert a substring into a string Popular Usage: string.insert(start posi:on, inser<on string) Example: string country = Back in the USSR ; // length is 16 cout << country.replace(14, 2, A ); cout << country.insert(15, BC ); // Displays Back in the USA // Displays Back in the USABC 11/2/17 Matni, CS16, Sp17 41

Content Changers: substr Use funcqon substr (short for substring ) to extract and return a substring of the string object Popular Usage: string.substr(start posi:on, # of places a@er start posi:on) Example: string city = Santa Barbara ; cout << city.substr(3, 5) // Displays ta Ba 11/2/17 Matni, CS16, Sp17 42

q HW 6 due Thu. 11/9 q Lab 5 due tomorrow Fri. 11/3 YOUR TO- DOs q New Lab 6 will be posted for Mon. 11/6 start q Visit Prof s and TAs office hours if you need help! q Eat at least one salad this week! 11/2/17 Matni, CS16, Fa17 43

11/2/17 Matni, CS16, Fa17 44