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.