Chapter 8 (Part 3) Library Classes for Strings (P.405)

Slides:



Advertisements
Similar presentations
File I/O in C++. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk);is stored on a secondary storage device.
Advertisements

Overview of Previous Lesson(s) Over View  In computing, a visual programming language (VPL) is any programming language that lets users create programs.
Programming File I/O. COMP102 Prog. Fundamentals File I/O / Slide 2 Copyright © 2000 by Brooks/Cole Publishing Company A division of International Thomson.
File I/O. COMP104 Lecture 20 / Slide 2 Using Input/Output Files * A computer file n is stored on a secondary storage device (e.g., disk) n is permanent.
Chapter 10.
File I/O. COMP104 Lecture 20 / Slide 2 Using Input/Output Files (Review) * A computer file n is stored secondary storage devices (hard drive, CD) n can.
File I/O. COMP104 File I/O / Slide 2 Using Input/Output Files * A computer file n is stored on a secondary storage device (e.g., disk) n is permanent.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Programming File I/O. COMP102 Prog. Fundamentals File I/O / Slide 2 Copyright © 2000 by Brooks/Cole Publishing Company A division of International Thomson.
Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
File I/O ifstreams and ofstreams Sections 11.1 &
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
FILE I/O IN C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
String Class. C-style and C++ string Classes C-style strings, called C-strings, consist of characters stored in an array ( we’ll look at them later) C++
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
1 Character Strings (Cstrings) Reference: CS215 textbook pages
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
An Introduction to Programming with C++ Sixth Edition Chapter 13 Strings.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Streams and Files Problem Solving, Abstraction, and Design using.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني I/O and File management Concept of streams. cin and cout objects. C++stream classes. Unformatted I/O.
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
Chapter 1.2 Introduction to C++ Programming
ifstreams and ofstreams
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 8 (Part 3) Library Classes for Strings (P.405)
Organizing Your Program Code (P.508)
CS Computer Science IA: Procedural Programming
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists File I/O Dr. Xiao Qin Auburn University.
What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
Characters, C-Strings, and More About the string Class
Basic Input and Output Operations
COMP 2710 Software Construction File I/O
Copyright © 2003 Pearson Education, Inc.
Standard Version of Starting Out with C++, 4th Edition
Chapter 2 part #3 C++ Input / Output
Working with Strings Lecture 2 Hartmut Kaiser
10.1 Character Testing.
Today’s Lecture I/O Streams Tools for File I/O
Chapter 9 File Streams Computing Fundamentals with C++ 3rd Edition
Introduction to C++ Programming
File I/O.
File I/O in C++ I.
Programming File I/O.
Programs written in C and C++ can run on many different computers
Standard Version of Starting Out with C++, 4th Edition
CHAPTER 4 File Processing.
Capitolo 1 – Introduction C++ Programming
Reading from and Writing to Files
Chapter 2 part #3 C++ Input / Output
Reading Data From and Writing Data To Text Files
Today’s Objectives 28-Jun-2006 Announcements
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Chapter 1 c++ structure C++ Input / Output
File I/O in C++ I.
Reading from and Writing to Files
Presentation transcript:

Chapter 8 (Part 3) Library Classes for Strings (P.405)

String Concatenation Good afternoon. Bob. Good afternoon. Charlie. #include <iostream> using std::cout; int main() { char a[] = "Good afternoon. "; char b[] = "Bob. "; char c[] = "Charlie. "; char newline[] = "\n"; char str[80] = ""; strcpy(str, a); strcat(str, b); strcat(str, newline); strcat(str, a); strcat(str, c); cout << str; return 0; } Good afternoon. Bob. Good afternoon. Charlie.

Powerful C++ Class #include <iostream> #include <string> using std::cout; using std::string; int main() { string a = "Good afternoon. "; string b = "Bob. "; string c = "Charlie. "; string newline = "\n"; string str; str = a + b + newline + a + c + newline; cout << str; return 0; }

Strings C language only has null-terminated strings which is stored as character arrays. char name[5] = "Mary"; C++ provides a string data type which is much easier to use. This class provides a bunch of powerful functions.

Creating String Objects string sentence = "This sentence is false."; string sentence("This sentence is false."); string bees(7, 'b'); string bees("bbbbbbb"); string letters(bees); string part(sentence, 5, 11); string part("sentence is"); the first character is at index position 0 string names[] = { "Alice", "Bob" }; string arrays

Input a string Read a character string into a string object: string sentence; cin >> sentence; However, cin will ignores leading whitespaces, and also terminates input when you enter a space, so for the input “This is a book”, only “This” is read into the object. Use the getline() function: getline(cin, sentence); ifstream fsIn("abc.txt"); getline(fsIn, sentence); the source of the input the destination for the input

Concatenating Strings Use the + operator to concatenate two string objects or a string object and a string literal. #include <iostream> #include <string> using std::cout; using std::endl; using std::string; int main() { string sentence1 = "This"; string sentence2 = "That"; string combined = sentence1 + "\n" + sentence2; cout << combined << endl; return 0; } This That

Concatenating Strings (2) You can also use the + operator to join a character to a string object sentence = sentence + '\n'; sentence += '\n'; sentence += "\n"; Length of a string sentence.length() // returns an integer sentence.empty() // returns true or false Ex8_14.cpp (P.408) size_t is defined using typedef statement to be equivalent to unsigned int. (P.154)

Accessing Strings Access a character in a string string sentence("Too many cooks spil the broth."); for (int i = 0; i < sentence.length(); i++) { if (' ' == sentence[i]) sentence[i] = '*'; } Use the at() member function if (' ' == sentence.at(i)) sentence.at(i) = '*'; Subscripting is faster, but the validity of the index is not checked.

Access a substring in a string Extract a part of an existing string object as a new string object. string sentence("Too many cooks spoil the broth."); string w = sentence.substr(4,10); // Extracts "many cooks"

Modifying Strings (1) Add one or more characters to the end of a string. string phrase("The higher"); string word("fewer"); phrase.append(1, ' '); // Append one space phrase.append("the "); // Append a string literal phrase.append(word); // Append a string object phrase.append(2, '!');// Append two exclamation marks When you call append(), the function returns a reference to the object, so you could write the above calls in a single statement: phrase.append(1, ' ').append("the ").append(word).append(2, '!');

Modifying Strings (2) Insert a string in the interior of another string: (P.412) string word("ABCDEF"); string test("==="); word.insert(3, test); // word will become "ABC===DEF" Swap the contents of two string objects: string phrase("The more the merrier."); string query("Any"); query.swap(phrase);

Modifying Strings (3) Replace part of a string object string text("ABCDEF"); text.replace(2, 3, "->"); text will become “AB->F” Replacement with a null string will essentially delete that part. text = "AB->F"; text.replace(2, 2, ""); text will become “ABF”

Comparing Strings Operator overloading has been implemented for == != < <= > >= When two corresponding characters are compared, their ASCII codes determine which one is less than the other. "USA" < "unique" If no character pairs are found to be different, the string with fewer characters is less. "book" < "books"

Ex8_15.cpp (P.415) in main(): nstrings: # of input strings maxwidth: maximum length of input strings string* sort(string* strings, size_t count) Actually the return type can be void in this example.

Search Strings Four versions of the find() function: string phrase("So near and yet so far"); string str("So near"); cout << phrase.find(str) << endl; // Outputs 0 (starting position) cout << phrase.find("so far") << endl; // Outputs 16 cout << phrase.find("so near") << endl; // Outputs string::npos = 4294967295 on MS VC++ The function returns the value string::npos if the item was not found. The value of string::npos may vary with different C++ compilers, so you should always use string::npos and not the explicit value.

Search Strings (2) Searching from a specified position: string phrase("ABCDEABCDEABCDE"); cout << phrase.find("A"); // Outputs 0 cout << phrase.find("A", 3); // Outputs 5 cout << phrase.find("A", 11); // Outputs string::npos = 4294967295

Handling Chinese Characters #include <iostream> #include <string> using std::cout; using std::string; int main() { string myString = "暨南大學"; string str2 = "中文"; cout << myString << myString.length() << '\n'; cout << str2.substr(3,3) << myString.substr(6,3) << '\n'; return 0; // length() size() are measured in } // bytes, not characters.

Exercise: Splitting Chinese Characters Write a program to read a line from the user. That line may contain both English and Chinese characters, and punctuation and spaces. Store the line as a string. Then print each character in a separate line. e.g., msg = "物聯網(IoT)"; 物 聯 網 ( I o T )

File I/O

Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide input data to a program or receive output data from a program, or both; must reside in Project directory (not necessarily the same directory as the .cpp files) must be opened before it is used.

C Functions for File I/O In function-oriented programming, we use the following functions to access disk files: fopen() fclose() fread() fwrite() fprintf() In object-oriented programming, we use a well-prepared class “fstream”.

C++ Classes for Input / Output stream - a sequence of characters interactive (iostream)  cin - input stream associated with keyboard.  cout - output stream associated with display. file (fstream)  ifstream - defines new input stream (normally associated with a file).  ofstream - defines new output stream (normally associated with a file).

Input File-Related Functions #include <fstream> ifstream fsIn; fsIn.open("fname.txt") connects stream fsIn to the external file "fname.txt". fsIn >> c; //Behaves just like cin fsIn.close() disconnects the stream and associated file.

Output File-Related Functions #include <fstream> ofstream fsOut; fsOut.open("fname.txt") connects stream fsOut to the external file "fname.txt". fsOut << c; //Behaves just like cout fsOut.close() disconnects the stream and associated file.

Example 1 #include <iostream> #include <fstream> using namespace std; int main() { char FirstName[30], LastName[30]; int Age; char FileName[20]; cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName; cout << "Enter Age: "; cin >> Age; cout << "\nEnter the name of the file you want to create: "; cin >> FileName; ofstream Students(FileName, ios::out); Students << FirstName << "\n" << LastName << "\n" << Age; cout << "\n\n"; return 0; } The file will be created in the directory where your “.cpp” file resides. e.g. “D:\VisualStudio2010\Projects\YourProject\YourProject”

Example 2 #include <iostream> #include <fstream> using std::cin; using std::cout; using std::ofstream; int main() { char FirstName[30], LastName[30]; int Age; // char FileName[20]; string FileName; // Length may be greater than 20 if full pathname is specified. cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName; cout << "Enter Age: "; cin >> Age; cout << "\nEnter the name of the file you want to create: "; cin >> FileName; ofstream Students(FileName); Students << FirstName << "\n" << LastName << "\n" << Age; Students.close(); return 0; }

Example 3: Output to a File #include <fstream> #include <iostream> using std::cout; using std::endl; using std::ofstream; int main() { ofstream Student("message.txt"); Student << "HELLO\n"; Student << "HI\n"; return 0; }

Example 4 – Input from a File #include <iostream> #include <fstream> using std::cin; using std::cout; using std::ifstream; int main() { char FirstName[30], LastName[30]; int Age; char FileName[20]; cout << "Enter the name of the file you want to open: "; cin >> FileName; ifstream Students(FileName); Students >> FirstName >> LastName >> Age; Students.close(); cout << "\nFirst Name: " << FirstName; cout << "\nLast Name: " << LastName; cout << "\nEnter Age: " << Age; cout << "\n\n"; return 0; }

Exercise: ifstream There are 100 lines in "/home2/ncnu/ifstream100.dat".  There is exact one integer in a line. Write a program and use the "ifstream" class to read data from this file. Calculate the sum of these numbers. Extend your program to read the filename from the user. It should be able to handle unlimited number of lines with the following indefinite loop: while (fsIn >> n) { sum += n; count++; } Test your program with /home2/ncnu/ifstream100.dat /home2/ncnu/ifstream5.dat