Lecture+16 - Engineering 101 Engineering 101/30/07 Strings...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Engineering 101 Engineering 101 Lecture 16 10/30/07 Strings and Generic Types Quote of the Day Quote of the Day Success is a lousy teacher. It seduces smart people into thinking they can't ­ Bill Gates lose. Project 5 Project 5 What will be the What will be the 1st cout in the code? 1­ 2 10 2­ 2 12 3­ 5 10 4­ 3 13 What will be the What will be the 1st cout in the code? 1­ 2 10 2­ 2 12 3­ 5 10 4­ 3 13 What will be the What will be the 2nd cout in the code? 1­ 2 10 2­ 2 12 3­ 4 14 4­ 3 13 What will be the What will be the 2nd cout in the code? 1­ 2 10 2­ 2 12 3­ 4 14 4­ 3 13 What will be the What will be the 3rd cout in the code? 1­ 2 10 2­ 2 14 3­ 4 14 4­ 3 13 What will be the What will be the 3rd cout in the code? 1­ 2 10 2­ 2 14 3­ 4 14 4­ 3 13 #include <iostream> using namespace std; int a=5, b=10; void proc(int & a){ a = a + 1; b = b + 1; return; } int main(){ cout << a << “ “ << b << endl; proc(b); int a=2; cout << a << “ “ << b << endl; proc(a); cout << a << “ “ << b << endl; return 1; } Example 1 Example 1 The String Class The String Class So far we have considered problems where the data we are manipulating is primarily numbers. Often the data we want to work with is not number, but rather text. The String Class The String Class The string class provides a way of manipulating text objects. To use the string class you must include it by putting an include line at the top of your C++ program: #include <string> Declaring a String Declaring a String To declare a string: string firstname; To assign a value to a string string firstname(“Peter”); or string firstname = “Peter”; String literals are in “double­quotes” Assigning a String Assigning a String You could do the same thing in two steps: string firstname; firstname = “Peter”; Adding Strings Adding Strings You can add strings together string firstname(“Peter”); string lastname(“Parker”); string fullname, occupation; fullname = firstname + “ “ + lastname; occupation = “superhero”; String Output String Output You can send strings to files and standard output using << cout << “Name : ” << fullname << endl; cout << “Job: “ << occupation << endl; String Input String Input One function in the string class is useful for reading a line of data: istream& getline(istream& in, string & line) getline will read a whole line from the istream in and put it in line typically we don’t use the fact that getline returns the istream in when it is called Comparing Strings Comparing Strings s < s2 Evaluates alphabetic order s > s2 s == s2 s <= s2 s >= s2 Note, however, that upper and lowercase letters are considered different. Uppercase letters come before lowercase letters alphabetically. Spaces and other characters are counted also. The Nature of Strings The Nature of Strings Strings are really lists of chars. The offset is an integer that tells how far from the front of the string a particular character lies. Strings support array semantics. This means you can reference any character by typing: identifier[offset] Referencing Characters Referencing Characters For example: string s = “New_York” cout << s[0] << s[4] << endl; char char 0 1 2 3 4 567 NY Determine what it prints Determine what it prints 1 – A statement about man’s fallibility 2 – A statement about voting rights 3 – A statement about historical fashion 4 – A statement about Italian travel Determine what it prints Determine what it prints 1 – A statement about man’s fallibility 2 – A statement about voting rights 3 – A statement about historical fashion 4 – A statement about Italian travel How the string changes How the string changes To_err_is_human Togerr_is_human Togarr_is_human Togarr_is_Ruman Togarr_is_Roman Toga___is_Roman Determine what it prints Determine what it prints 1 – A statement about man’s fallibility 2 – A statement about voting rights 3 – A statement about historical fashion 4 – A statement about Italian travel Determine what it prints Determine what it prints 1 – A statement about man’s fallibility 2 – A statement about voting rights 3 – A statement about historical fashion 4 – A statement about Italian travel How the string changes How the string changes Oxifhumaxfoxifboti One_human_one_vote Referencing Warning Referencing C++ allows you to reference outside the range!! string s(“Michigan”); cout << s[­1] << s[10]<<endl; This will produce some unpredictable results! Referencing Warning Referencing Worse still you can assign to undefined reference locations string s(“Michigan”); s[­1] = ‘x’; s[10] = ‘Y’; This will write into memory. Unused memory? Other variables used in this program? The execution code of your program? The execution code of your editor? Referencing Warning Referencing Consequences: Unanticipated results when data is changed in an unaddressed identifier. Program crashes: “Segmentation Fault” “General protection fault” Computer crashes (rare). Referencing Warning Referencing Why? s[0] memory M i c h i g a n Referencing Warning Referencing Why? s[1] memory M i c h i g a n Referencing Warning Referencing Why? s[5] memory M i c h i g a n Referencing Warning Referencing Why? s[10] memory M i c h i g a n •We don’t know what could be in this memory location. It could be anything. It could be used by the program or another program. Strings: at( ) Strings: at( ) We can use the safer version of addressing, the at method string t(“Silence”); t.at( 2 ) = t.at( 1 ); t.at( 1 ) = ‘c’; cout << t << endl; The at( ) method checks to see that you don’t address beyond the length of the string. It does not always check for negative addresses. Other String Methods Other String Methods s.size( ) s.append(s2) s.push_back(c) s.find(s2) Number of chars in the string Appends s2 to s Appends char c to s Search for s2 in s and returns the location of the first character of the first match starting with zero or s.npos if not found string s(“alex”); cout << s.find(“ex”); // outputs 2 if(s.find(“la”) == s.npos){ cout << “didn’t find la in ” << s << endl; } More Methods More Methods s.insert(offset, s2) Insert s2 in s starting at offset s.erase(offset, num) erase num chars from s s.replace(offset, num, s2) erase plus insert s.substr(offset, len) returns a new string that is the part of s that starts at offset and is len long ichi string mystring(“Michigan”); cout << mystring.substr(1,4); Read in a file line by line until the end of the file. Determine if the line contains the words “have to” If so, replace them with the words “want to” Print the line to standard output. I have to do my laundry I have to do my project I have to learn C++ I have to study tonight I want to do my laundry I want to do my project I want to learn C++ I want to study tonight Write a Program That Write a Program That Instills Positivity getline (istream&, string&) get a line istream.fail( ) istream failed string.find(string2) == string.npos didn’t find string2 string.replace(offset, num, string2) replace part of string by string2 1: Example: Which Program Works? Example: Which Program Works? 2: 3: 1: Example: Which Program Works? Example: Which Program Works? 2: 3: 4: Positivity Program Positivity Program string line; ifstream in(“textfile”); getline(in,line); while(!in.fail()){ n = line.find(“have to”); while (n != line.npos){ line.replace(n,7,”want to”); n = line.find(“have to”); } cout << line << endl; getline(in,line); } News Flash! FAA gets ready for Air Traffic Control 2.0 News Flash! News Flash! Nearly 30 percent of all flights arrived late between January and August in 2007 U.S. flights projected to double in the next 20 years The current air­traffic­control system will be effectively gridlocked by 2015 News Flash! News Flash! Replace the current radar­powered air­traffic­control network with one that relies on GPS and advanced avionics (called NextGen) Estimated to cost $15 to $22 billion Planes will be able to see the location of other planes and also weather while transmitting their own locations to other planes and ground stations Humans are still pretty good though: http://www.youtube.com/watch?v=6­RuVR7LLek http://www.youtube.com/watch?v=JdrSBzy8NwQ Strings and C­strings Strings and C­strings It is important to note that the string class is a more modern version of a more basic type called the C­string. The literals we have used (e.g. “hello”) are really C­strings. Sometimes functions expect C­strings s.c_str( ) will return the C­string equivalent of the string s Strings and C­strings Strings and C­strings One place this is required is when specifying file names for opening fstreams string filename; cout << “Enter Filename:”<< endl; getline(cin, filename); ifstream in(filename.c_str( ) ); Generally we pass by value if we don’t want to change the variable and by reference if we do pass-by-value int function( int x, int y); Passing Strings to Functions and Passing Strings to Functions and Procedures a copy is made for use in the function pass-by-reference access is given to the original data void procedure ( int & x, int & y); With strings we sometimes want to avoid recopying the string. It takes memory and time. To overcome this we can pass as a constant reference rather than by value int function( const string & x, const string &y); Passing Strings to Functions and Passing Strings to Functions and Procedures constant pass-by-reference read-only access is given to the original data void procedure ( string & x, string & y); pass-by-reference full access is given to the original data Generic Types Generic Types Sometimes we may want to write a function but make it useful for multiple data types. Example: What if we want to swap two numbers? We can’t just type: a=b; b=a; (Why?) Generic Types Generic Types Consider the function: void swap (int & a, int & b) { int c=a; a=b; b=c; return; } Generic Types Generic Types This definition is only valid for integers although the procedure could work for most anything void swap (int & a, int & b) { int c=a; a=b; b=c; return; } Generic Types Generic Types This definition is only valid for integers although the procedure could work for most anything template <class T> void swap (T& a, T & b) { T c=a; a=b; b=c; return; } Generic Types Generic Types Using the Generic swap procedure: main ( ) { int a=5, b=4; string s(“hello”), t(“world); swap(a, b); swap(s, t); } Complex Numbers #include <complex> Complex numbers can be made up of doubles, integers or other numeric types depending on how you want to represent the real and imaginary parts. complex<double> c1(1.0, 2.5); complex<int> c2(2, 0); Classes that Use Classes that Use Generic Typing The pair type #include <utility> Represents a generic pair of two numbers. For example if you want to make a string associated with a number: pair<int, string> a; a.first = 1; a.second= “The first string.”; Classes that Use Classes that Use Generic Typing Next Lecture Next Lecture Vectors and Vectors of Vectors ...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online