The Standard String Class Is actually a template: –typedef basic_string string This means you can have strings of things other than chars.

Slides:



Advertisements
Similar presentations
LECTURE 17 C++ Strings 18. 2Strings Creating String Objects 18 C-string C++ - string \0 Array of chars that is null terminated (‘\0’). Object.
Advertisements

IOStreams CNS 3370 Copyright 2003, Fresh Sources, Inc.
File streams Chapter , ,
Definition of Strings Generally speaking, a string is a sequence of characters c string c++ string class Examples: “hello”, “high school”, “H2O”. Typical.
Today’s Class Class string –The basics –Assignment –Concatenation –Compare & swap –Find –Conversion to C-style char * strings –Iterators.
. Plab – Tirgul 8 I/O streams Example: string class.
Engineering Problem Solving With C++ An Object Based Approach Chapter 6 One-Dimensional Arrays.
 2006 Pearson Education, Inc. All rights reserved Class string and String Stream Processing.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 12 More.
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
Streams, Files. 2 Stream Stream is a sequence of bytes Input stream In input operations, the bytes are transferred from a device to the main memory Output.
Program Input and the Software Design Process ROBERT REAVES.
Unformatted and Formatted I/O Operations. 2 Unformatted Input/output is the most basic form of input/output. Unformatted I/O transfers the internal binary.
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.
C++ Programming Certificate University of Washington Cliff Green
1 Advanced Input and Output COSC1567 C++ Programming Lecture 9.
Chapter 8 Strings and Vectors (8.1 and 8.2). An Array of characters Defined as: char firstName[20]; char firstName[] = {‘T’, ‘i’, ‘m’}; // an array of.
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.
String Constructors string str; // creates an empty //string string str(“abc”); // creates a string // from a C-string string str(aString); // creates.
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
Working with Strings Lecture 2 Hartmut Kaiser
Chapter 6 One-Dimensional Arrays ELEC 206 Computer Tools for Electrical Engineering.
CSE 232: C++ Input/Output Manipulation Built-In and Simple User Defined Types in C++ int, long, short, char (signed, integer division) –unsigned versions.
C ++ Programming Languages Omid Jafarinezhad Lecturer: Omid Jafarinezhad Fall 2013 Lecture 2 Department of Computer Engineering 1.
File I/O ifstreams and ofstreams Sections 11.1 &
1 Streams In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
Define our own data types We can define a new data type by defining a new class: class Student {...}; Class is a structured data type. Can we define our.
COP 3530 Data Structures & Algorithms Discussion Session 3.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
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.
The C++ Programming Language Streams. Contents u Output Stream u Input Stream u Formatting u Manipulators u Files & Streams.
C++ Streams © Bruce M. Reynolds & Cliff Green, C++ Programming Certificate University of Washington Cliff Green.
1 I/O  C++ has no built-in support for input/output input/output is a library (iostream)  C++ program views input and output as a stream of bytes  Input:
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
1 Today’s Objectives  Announcements Turn in Homework 4 Quiz 4 will be on Wednesday, July 19 – It will have questions about inheritance, polymorphism,
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++
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
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.
Chapter -7 Basic function of Input/output system basics and file processing Stream classes : I/O Streams. A stream is a source or destination for collection.
CS  Inserters and Extractors  Stream State  Files Streams  String Streams  Formatting  Manipulators  Internationalization.
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
UNIT VI Streams & Files in C++: Stream classes, stream errors, disk file I/O with streams, File pointers, Error handling in file I/O. File I/O with members.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
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.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
CSCI 333 Data Structures I/O with C++ 20 October, 2003.
Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in.
Strings, and the string Class. C-Strings C-string: sequence of characters stored in adjacent memory locations and terminated by NULL character The C-string.
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
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.
Introduction to C++ (Extensions to C)
Class string and String Stream Processing: A Deeper Look
Output Stream Formatting
C++ STRINGS string is part of the Standard C++ Library
Working with Strings Lecture 2 Hartmut Kaiser
Operator Overloading; String and Array Objects
10.1 Character Testing.
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Class string and String Stream Processing
Engineering Problem Solving with C++, Etter
File I/O.
Today’s Objectives 28-Jun-2006 Announcements
Presentation transcript:

The Standard String Class Is actually a template: –typedef basic_string string This means you can have strings of things other than chars

Accessing Elements You can access the elements via the subscript operator std::string fred = "hello"; std::cout << fred[0]; Or through the at method std::string fred = "hello"; std::cout << fred.at(0); at() throws an out_of_range on bad access

Constructors C-style string, string, char sequence, and parts there-of string s1; // default - empty string string s2 = "hello"; // C-style string string s3(5,'h'); // ”hhhhh” string s4 = s3; //copy of s3 string s5(s2,1,2); // ”el” const char *cp = "hello"; string s6(cp+1,2); //"el" again string s7(cp,1,2); //func. resolution

Assignment Lot's of versions again string s1 = "family"; string s2 = "guy"; s1 = s2; // assign a string s1 = "fred"; // assign a C-style string s2 = 'h'; // assign a char There are also assign() methods for other constructor equivalents (since assignment operators can’t have multiple arguments)

Comparisons Operator overloading provides for string and c-style string compares There are also compare methods which return ints ala strcmp The simple =,>,!= usually suffice though

Appending  += is overloaded for appending strings, c-style strings, and chars  There is also an append method: string& append(const string &str); string& append(const string &str, size_type pos, size_type n); string& append(const char *p, size_type n); string& append(const char *p); string& append(size_type n, char c);

Insertion  Similar to appending, but a position is required  The characters are inserted before the position string& insert(size_type pos, const string &str); string& insert(size_type pos, const string &str, size_type pos1, size_type n); string& insert(size_type pos, char *p, size_type n); string& insert(size_type pos, char *p, size_type n); string& insert(size_type pos, size_type n, char c);

Concatenation Performed via an overloaded + operator Works for strings And C-style strings And chars

Searching  Can search for strings, C-style strings, and chars  Can find first or last occurance of the item  Or first or last occurance of any of the items elements  Or first or last occurance of any characters not in the item

Searching std::string s = "accdcde"; s.find("cd"); //return 2 s.rfind("cd"); //returns 4 s.find_first_of("cd"); //returns 1 s.find_last_of("cd"); // returns 5 s.find_first_not_of("cd");//returns 0 s.find_last_not_of("cd"); //returns 6

Replace  Replaces a substring with another string  Has as many forms as the constructors string& replace(size_type i, size_type n, const string &str); string& replace(size_type i, size_type n, const string &str, size_type i2, size_type n2); string& replace(size_type i, size_type n, const char *p, size_type n2); string& replace(size_type i, size_type n, const char *p); string& replace(size_type i, size_type n, size_type n2, char c);

Substring Returns a new string object representing the substring string substr(size_type i, size_type n) const Combines well with find and replace

Misc. Methods  length() and size() give the string length  max_size() gives the maximum size of a string  empty() returns true if the string is empty  erase(size_type i=0, size_type n=npos) empties the string  Notice that erase() can be done with replace()

Converting to C-Style Strings The c_str() method returns a const char* The data() method is similar but does not add the '\0’ The array returned is managed by the string Calling a non-const method invalidates it

Input/Output strings can be output with operator<< They can be input with operator>> in which case words are read There is also a getline(istream&,string&) function getline reads a line from input into the string Input into strings is better than char arrays Mainly because the string will expand as necessary

The Standard Streams Yet another template you have been using without knowing typedef basic_ostream ostream Same reasons as string for being a template

Output Streams  You should know how to use these by now  You should know how to overload << by now  Note that operator<< aren't members and thus aren't virtual  When dealing with inheritance it is common to: class Base { virtual ostream& put(ostream &os) const; }; ostream& operator<<(ostream& os, const Base &b) { return b.put(os); }

Input Streams Again you should have some experience with these by now Virtual functions don't matter as much But the same technique can be used Should always test the result of a read and not just assume it worked

Stream State All istream and ostream’s have the following methods bool good() const true if all has gone well bool eof() const true if reached end of input bool fail() const true if next operation will fail bool bad() const true if stream may be corrupt

Formatting We can change the format that C++ uses to output values The setf() and unsetf() methods are used The flags we can use are defined in ios_base cout.setf(ios_base::oct,ios_base::basefield) –ouput integers in octal cout.setf(ios_base::scientific, ios_base::floatfield) –output floating point in scientific format

Formatting II Can also set field widths and fill characters width() and fill() are used cout.width(4); cout.fill('*'); cout << "hi"; //will output '##hi' We can use left, right, and internal in ios_base to change placement Changes only apply to the next output operation

Manipulators Manipulators are a simpler way of manipulating streams They are used in the standard << output notation std::cout << 12 << ' ' << oct << 12 << endl; std::cout << setw(4) << setfill('*') << "hi"; You need to #include

File Streams Reading and writing from files is the same as using cin and cout Except you have to open them first ifstreams are for reading files ofstreams are for writing files fstreams are for additional options (read and write, append mode, etc)

Strstreams  A string in memory can also be used as a stream  Our compiler and the standard disagree on this bit.  strstream has been replaced with stringstream (which acts on string obects insted of char*s)  Our compiler doesn’t support stringstreams.

Input String Streams #include void word(const char* s) { istrstream istr(s); string w; while (istr >> w) cout << w << endl; } int main() { word("here is a short string"); }

Output String Streams #include int main() { char a[100] = ""; ostrstream out(a,100); out << setw(50) << setfill('*') << "a string" << endl; cout << a; }

Closing Streams The close() method closes a stream Usually it is not needed as the destructor performs the close Sometimes closing a file can be useful, though