Std Library of C++.

Slides:



Advertisements
Similar presentations
Programming Character I/O. COMP102 Prog. Fundamentals I: Character I/O/ Slide 2 More on char Type l Constant Declaration: const char star = '*'; l Variable.
Advertisements

Character I/O. COMP104 Character I/O Slide 2 Data Type: char * Constant declaration const char star = '*'; * Variable declaration char resp; * Variable.
Characters. COMP104 Lecture 21 / Slide 2 Data Type: char * Constant declaration const char star = '*'; * Variable declaration char resp; * Variable assignment.
© 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5/e Starting Out with C++: Early Objects 5 th Edition Chapter 2 Introduction.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
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.
C++ Introduction. Why Learn C++? Very powerful and respected prog. Lang. Very powerful and respected prog. Lang. Highly respected in Academics Highly.
C++ crash course Class 3 designing C++ programs, classes, control structures.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Seventh.
1 Chapter 10 Characters, Strings, and the string class.
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.
Working with Strings Lecture 2 Hartmut Kaiser
February 14, 2005 Characters, Strings and the String Class.
Chapter 1 Working with strings. Objectives Understand simple programs using character strings and the string library. Get acquainted with declarations,
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
CSE 232: C++ Input/Output Manipulation Built-In and Simple User Defined Types in C++ int, long, short, char (signed, integer division) –unsigned versions.
Copyright © 2012 Pearson Education, Inc. Chapter 10: Characters, C- Strings, and More About the string Class.
Dynamic Memory. We will follow different order from Course Book We will follow different order from Course Book First we will cover Sect The new.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10: Characters, Strings, and the string class.
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
Characters, Strings, And The string Class Chapter 10.
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 
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 10: Characters, C- Strings, and More About.
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.
CSC 270 – Survey of Programming Languages
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
Chapter Characters, Strings, and the string class 10.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
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.
1 ENERGY 211 / CME 211 Lecture 7 October 6, 2008.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
A Sample Program #include using namespace std; int main(void) { cout
Basic Elements Skill Area 313 Part B. Lecture Overview Basic Input/Output Statements Whitespaces Expression Operators IF Statements Logical Operators.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Strings.
Bill Tucker Austin Community College COSC 1315
Note: Some of the slides are repeated from Introduction to C++
Introduction Programs which manipulate character data don’t usually just deal with single characters, but instead with collections of them (e.g. words,
C++ Exceptions.
Chapter Topics The Basics of a C++ Program Data Types
Strings CSCI 112: Programming in C.
C-Strings We have already seen that a C-string is a null-terminated array of characters.
Chapter 2: Introduction to C++
Programming Fundamentals
CS31 Discussion 1E Jie(Jay) Wang Week5 Oct.27.
Computing Fundamentals
Basic Elements of C++.
C++ Standard Library.
Working with Strings Lecture 2 Hartmut Kaiser
Characters, C-Strings, and More About the string Class
Standard Version of Starting Out with C++, 4th Edition
Chapter 2: Introduction to C++
Basic Elements of C++ Chapter 2.
Working with Strings Lecture 2 Hartmut Kaiser
10.1 Character Testing.
Chapter 3: Input/Output
Introduction to C++ Programming
Chapter 2: Introduction to C++.
Standard Version of Starting Out with C++, 4th Edition
C++ Introduction - 3.
Using string type variables
ENERGY 211 / CME 211 Lecture 9 October 10, 2008.
Chapter 1 c++ structure C++ Input / Output
character manipulation
Presentation transcript:

std Library of C++

std Library Standard C++ Library Has a lot of useful classes or abstract data types cin, cout, and cerr – already seen. They are objects of istream or ostream classes. string and vector are perhaps the next most important of the std library classes

std namespace A namespace allows programmers to avoid collisions with same names for classes in different libraries. Class names (and other names like objects cout, cin etc.) of Standard library are defined in the std namespace cout of std namespace is different from, say, cout of xyz namespace.

std namespace … std::cout specifies both namespace and object name within the namespace Cumbersome to use std:: prefix everytime an object or class of std namespace is used Solution is the ‘using declaration’

using declaration using namespace::name; After the above declaration name can be used without specifying the namespace #include <iostream> // using declarations states our intent to use these names from the namespace std using std::cout; int main() { cout << “Rama”; // ok: cout is now a synonym for std::cout }

using declaration … using namespace namespace-name; After the above declaration compiler automatically searches in this namespace to resolve names #include <iostream> // using declarations states our intent to use these names from the namespace std using namespace std; int main() { cout << “Rama”; // ok: compiler finds cout in std namespace }

Using declaration … using namespace std; May result in unintended resolution of names to std namespace So ‘using std::cout’ style is superior But ‘using namespace std;’ is quite convenient So can be used for our course work And can also be used in real life C++ programs where too many namespaces are not involved

string class of std library string supports variable-length character strings Manages the memory associated with storing the characters of the string Provides useful operations Is efficient enough for general usage #include <string> using std::string;

string constructors string s1; string s2(s1); string s3("value"); //Default constructor; s1 is an empty string string s2(s1); //Initialize s2 as a copy of s1 string s3("value"); //Initialize s3 as a copy of the string literal string s4(10, 'c'); //Initialize s4 with 10 copies of the character 'c'

Simple program using string // book code: 3/string_io.cc #include <string> using namespace std; int main() { string s; // empty string cin >> s; // read whitespace-separated string into s cout << s << endl; // write s to the output return 0; }

Reading strings till end of file See word_echo.cc Data file is data/word_echo Note that: even if multiple words are present on the same line in the input each word is printed on a separate line in the output The >> operator return the istream object that it read. That istream object evaluates to false on end of file/data.

Read a full line at a time See getline.cc getline is a function defined in <string>. It is not a member function of string class getline takes an istream object (say cin) and a string object as arguments getline reads a line of input including the newline character and Stores the line of input excluding the newline character in its string argument.

Read a full line at a time Empty line will be read into empty string getline returns an istream object whose value can be tested for false (end of data returns false) Compare word_echo with getline by running them with same data

string comparison s1 == s2 string big = "big", small = "small"; // Returns true if s1 and s2 are equal; false otherwise string big = "big", small = "small"; if (big == small) // false // ...

Observation 3Ob1.txt Study and run the example programs that have been studied so far (and given below for your easy reference) and put down your observations in the file 3Ob1.txt. The example programs are: string_io.cc word_echo.cc getline.cc

Assignment 3A Write a program that reads words from standard input and writes it to standard output. However the following words should NOT be written to standard output: and, or in, on, of The, the

Assignment 3B Write a program that reads from standard input and outputs the number of words as well as the number of lines in it.

Common string operations s.empty() //Returns true if s is empty; otherwise returns false s.size() // Returns number of characters in s s[n] // Returns the character at position n in s; positions start at 0. s1 + s2 // Returns a string equal to the concatenation of s1 and s2 s1 = s2 // Replaces characters in s1 by a copy of s2 s1 == s2 // Returns true if s1 and s2 are equal; false otherwise !=, <, <=, >, and >= Have their normal meanings

Size of string See string_size.cc string::sizetype is the type of the return value of string::size() We don’t need to know exact type of sizetype except that it is a numeric (unsigned) type and so can be used in all operations that an unsigned type can be used. Sizetype allows us to be machine independent. E.g. On some machines it may be unsinged int and on some others it may be unsigned long.

string comparison string big = "big", small = "small"; string s1 = big; // s1 is a copy of big if (big == small) // false // ... if (big <= s1) // true, they're equal, so big // is less than or equal to s1

string comparison … If two strings have different lengths and if every character in the shorter string is equal to the corresponding character of the longer string then the shorter string is less than the longer one. If the characters in two strings differ, then we compare them by comparing the first character at which the strings differ. As an example, given the strings string substr = "Hello"; string phrase = "Hello World"; string slang = "Hiya"; then substr is less than phrase, and slang is greater than either substr or phrase See strcompare.cc

string assignment Assignment of one string to another results in a copy of one string in another string st1; string st2 = "The expense of spirit"; st1 = st2; // replace st1 by a copy of st2 st1 and st2 have different memory areas but their data contents are similar. This is different from char pointer assignments

Char pointer assignment char *s = null char *p = “The expense of spirit”; s = p; Now both s and p point to same memory area

Adding strings string s1("hello, "); string s2("world\n"); string s3 = s1 + s2; // s3 is hello, world\n s1 += s2; // equivalent to s1 = s1 + s2

Adding string literals and strings string s1("hello"); string s2("world"); string s3 = s1 + ", " + s2 + "\n"; s3 will be “hello, world\n”

Adding strings and literals … string s1 = "hello"; // no punctuation string s2 = "world"; string s3 = s1 + ", "; // ok: adding a string and a // literal string s4 = "hello" + ", "; // error: no string operand string s5 = s1 + ", " + "world"; // ok: each + has string // operand string s6 = "hello" + ", " + s2; // error: can't add string literals s7 = string(“hello”) + “,” + s2; // ok

Fetching a char from a string string str("some string"); for (string::size_type ix = 0; ix != str.size(); ++ix) cout << str[ix] << endl; str[ix] = '*';

lvalue and rvalue string str(“Rama”); str[2] is an lvalue lvalue (pronounced "ell-value"): An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment. str[2] = ‘a’; //Is a valid expression as str[2] //an lvalue Variables are lvalues

rvalue rvalue (pronounced "are-value"): An expression that is an rvalue may appear on the right- but not left-hand side of an assignment. Literals are rvalues “Rama” is an rvalue “Rama” = “abc”; //Error. “Rama” is an //rvalue and so cannot be on //lhs of assignment expression

lvalue and rvalue Sometimes compiler errors will refer to lvalue or rvalue. So it is useful to know the terms

Functions dealing with char <cctype> header defines the functions. The functions are: isalnum(c) true if c is a letter or a digit isalpha(c) true if c is a letter iscntrl(c) true if c is a control character isdigit(c) true if c is a digit isgraph(c) true if c is not a space but is printable islower(c) true if c is a lowercase letter

Functions dealing with char isprint(c) true if c is a printable character ispunct(c) true if c is a punctuation character isspace(c) true if c is whitespace isupper(c) true if c is an uppercase letter isxdigit(c) true if c is a hexadecimal digit tolower(c) If c is an uppercase letter, returns its lowercase equivalent; otherwise returns c unchanged toupper(c) If c is a lowercase letter, returns its uppercase equivalent; otherwise returns c unchanged.

Example program for char functions See cctype.cc

Assignments Exercise 3.7: Write a program to read two strings and report whether the strings are equal. If not, report which of the two is the larger. Now, change the program to report whether the strings have the same length and if not report which is longer. Exercise 3.8: Write a program to read strings from the standard input, concatenating what is read into one large string. Print the concatenated string. Next, change the program to separate adjacent input strings by a space.

Assignments … Exercise 3.10: Write a program to strip the punctuation from a string. The input to the program should be a string of characters including punctuation; the output should be a string in which the punctuation is removed.

Book Source Code Copyright Note The course book is C++ Primer, 4th Edition by Lippman, Lajoie and Moo. Any references in earlier files to source files, and use of code within those files, are of example code given in and/or along with the book. As these slides are freely accessible on the Internet, not-for-profit, and for educational purposes, based on the permission related statements in the source code, I have considered that permission has been granted to use them in these slides.