Post on 15-Jan-2016
description
transcript
2003 Prentice Hall, Inc. All rights reserved.
1
Chapter 15 - Class string and String Stream Processing
Outline15.1 Introduction15.2 string Assignment and Concatenation15.3 Comparing strings15.4 Substrings15.5 Swapping strings15.6 string Characteristics15.7 Finding Strings and Characters in a string15.8 Replacing Characters in a string15.9 Inserting Characters into a string15.10 Conversion to C-Style char * Strings15.11 Iterators15.12 String Stream Processing
2003 Prentice Hall, Inc. All rights reserved.
2
15.1 Introduction
• Template class basic_string– String manipulation (copying, searching, etc.)
• typedef basic_string< char > string;• Also typedef for wchar_t
– Include <string>
• string initialization– string s1( "Hello" );– string s2( 8, 'x' );
• 8 'x' characters
– string month = "March"• Implicitly calls constructor
2003 Prentice Hall, Inc. All rights reserved.
3
15.1 Introduction
• No conversion from int or char– The following definitions are errors
• string error1 = 'c';• string error2( 'u' );• string error3 = 22;• string error4( 8 );
– However, can assign to one char if declared• s = 'n';
2003 Prentice Hall, Inc. All rights reserved.
4
15.1 Introduction
• string features– Not necessarily null terminated– length member function: s1.length()– Use [] to access individual characters: s1[0]
• 0 to length-1
– string not a pointer
– Many member functions take start position and length• If length argument too large, max chosen
– Stream extraction• cin >> stringObject;• getline( cin, s)
– Delimited by newline
2003 Prentice Hall, Inc. All rights reserved.
5
15.2 string Assignment and Concatenation
• Assignment– s2 = s1;
• Makes a separate copy
– s2.assign(s1);• Same as s2 = s1;
– myString.assign(s, start, N);• Copies N characters from s, beginning at index start
– Individual characters• s2[0] = s3[2];
2003 Prentice Hall, Inc. All rights reserved.
6
15.2 string Assignment and Concatenation
• Range checking– s3.at( index );
• Returns character at index• Can throw out_of_range exception
– [] has no range checking
• Concatenation– s3.append( "pet" );– s3 += "pet";
• Both add "pet" to end of s3
– s3.append( s1, start, N );• Appends N characters from s1, beginning at index start
2003 Prentice Hall, Inc.All rights reserved.
Outline7
fig15_01.cpp(1 of 3)
1 // Fig. 15.1: fig15_01.cpp2 // Demonstrating string assignment and concatenation.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <string>9 10 using std::string;11 12 int main()13 {14 string string1( "cat" );15 string string2; 16 string string3; 17 18 string2 = string1; // assign string1 to string219 string3.assign( string1 ); // assign string1 to string320 cout << "string1: " << string1 << "\nstring2: " << string221 << "\nstring3: " << string3 << "\n\n";22
String initialization and assignment.
Output
string1: cat
string2: cat
string3: cat
2003 Prentice Hall, Inc.All rights reserved.
Outline8
fig15_01.cpp(2 of 3)
23 // modify string2 and string3 24 string2[ 0 ] = string3[ 2 ] = 'r';25 26 cout << "After modification of string2 and string3:\n"27 << "string1: " << string1 << "\nstring2: " << string228 << "\nstring3: ";29 30 // demonstrating member function at31 for ( int i = 0; i < string3.length(); i++ ) 32 cout << string3.at( i );33 34 // declare string4 and string535 string string4( string1 + "apult" );36 string string5;37 38 // overloaded += 39 string3 += "pet"; // create "carpet" 40 string1.append( "acomb" ); // create "catacomb"41 42 // append subscript locations 4 through end of string1 to43 // create string "comb" (string5 was initially empty) 44 string5.append( string1, 4, string1.length() ); 45 46 cout << "\n\nAfter concatenation:\nstring1: " << string1 47 << "\nstring2: " << string2 << "\nstring3: " 48 << string3 << "\nstring4: " << string449 << "\nstring5: " << string5 << endl;50
After modification of string2 and string3:
string1: cat
string2: rat
string3: car
Note use of member function at instead of [].
After concatenation:
string1: catacomb
string2: rat
string3: carpet
string4: catapult
string5: comb
2003 Prentice Hall, Inc.All rights reserved.
Outline9
fig15_01.cpp(3 of 3)
fig15_01.cppoutput (1 of 1)
string1: cat
string2: cat
string3: cat
After modification of string2 and string3:
string1: cat
string2: rat
string3: car
After concatenation:
string1: catacomb
string2: rat
string3: carpet
string4: catapult
string5: comb
51 return 0;52 53 } // end main
2003 Prentice Hall, Inc. All rights reserved.
10
15.3 Comparing strings
• Overloaded operators– ==, !=, <, >, <= and >=– Return bool
• s1.compare(s2)– Returns positive if s1 lexicographically greater
• Compares letter by letter• 'B' lexicographically greater than 'A'
– Returns negative if less, zero if equal– s1.compare(start, length, s2, start,
length)• Compare portions of s1 and s2
– s1.compare(start, length, s2)• Compare portion of s1 with all of s2
2003 Prentice Hall, Inc.All rights reserved.
Outline11
fig15_02.cpp(1 of 4)
1 // Fig. 15.2: fig15_02.cpp2 // Demonstrating string comparison capabilities.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <string>9 10 using std::string;11 12 int main()13 {14 string string1( "Testing the comparison functions." );15 string string2( "Hello" ); 16 string string3( "stinger" );17 string string4( string2 );18
2003 Prentice Hall, Inc.All rights reserved.
Outline12
fig15_02.cpp(2 of 4)
19 cout << "string1: " << string1 << "\nstring2: " << string220 << "\nstring3: " << string3 << "\nstring4: " << string421 << "\n\n";22 23 // comparing string1 and string424 if ( string1 == string4 )25 cout << "string1 == string4\n";26 else { // string1 != string4 27 if ( string1 > string4 )28 cout << "string1 > string4\n";29 else // string1 < string430 cout << "string1 < string4\n";31 }32 33 // comparing string1 and string234 int result = string1.compare( string2 );35 36 if ( result == 0 )37 cout << "string1.compare( string2 ) == 0\n";38 else // result != 039 if ( result > 0 )40 cout << "string1.compare( string2 ) > 0\n";41 else // result < 042 cout << "string1.compare( string2 ) < 0\n";43
string1: Testing the comparison functions.
string2: Hello
string3: stinger
string4: Hello
string1 > string4
Note use of overloaded == operator.
2003 Prentice Hall, Inc.All rights reserved.
Outline13
fig15_02.cpp(3 of 4)
44 // comparing string1 (elements 2-5) and string3 (elements 0-5)45 result = string1.compare( 2, 5, string3, 0, 5 );46 47 if ( result == 0 )48 cout << "string1.compare( 2, 5, string3, 0, 5 ) == 0\n";49 else // result != 050 if ( result > 0 )51 cout << "string1.compare( 2, 5, string3, 0, 5 ) > 0\n";52 else // result < 053 cout << "string1.compare( 2, 5, string3, 0, 5 ) < 0\n";54 55 // comparing string2 and string456 result = string4.compare( 0, string2.length(), string2 );57 58 if ( result == 0 )59 cout << "string4.compare( 0, string2.length(), " 60 << "string2 ) == 0" << endl;61 else // result != 062 if ( result > 0 )63 cout << "string4.compare( 0, string2.length(), "64 << "string2 ) > 0" << endl;65 else // result < 066 cout << "string4.compare( 0, string2.length(), "67 << "string2 ) < 0" << endl;68
Note use of compare.
2003 Prentice Hall, Inc.All rights reserved.
Outline14
fig15_02.cpp(4 of 4)
fig15_02.cppoutput (1 of 1)
69 // comparing string2 and string470 result = string2.compare( 0, 3, string4 );71 72 if ( result == 0 )73 cout << "string2.compare( 0, 3, string4 ) == 0" << endl;74 else // result != 075 if ( result > 0 )76 cout << "string2.compare( 0, 3, string4 ) > 0" << endl;77 else // result < 078 cout << "string2.compare( 0, 3, string4 ) < 0" << endl;79 80 return 0;81 82 } // end main
string1: Testing the comparison functions.
string2: Hello
string3: stinger
string4: Hello
string1 > string4
string1.compare( string2 ) > 0
string1.compare( 2, 5, string3, 0, 5 ) == 0
string4.compare( 0, string2.length(), string2 ) == 0
string2.compare( 0, 3, string4 ) < 0
2003 Prentice Hall, Inc. All rights reserved.
15
15.4 Substrings
• Function substr gets substring– s1.substr( start, N );– Gets N characters, beginning with index start– Returns substring
2003 Prentice Hall, Inc.All rights reserved.
Outline16
fig15_03.cpp(1 of 1)
fig15_03.cppoutput (1 of 1)
1 // Fig. 15.3: fig15_03.cpp2 // Demonstrating string member function substr.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <string>9 10 using std::string;11 12 int main()13 {14 string string1( "The airplane landed on time." );15 16 // retrieve substring "plane" which17 // begins at subscript 7 and consists of 5 elements18 cout << string1.substr( 7, 5 ) << endl;19 20 return 0;21 22 } // end main
plane
Note usage of substr.
2003 Prentice Hall, Inc. All rights reserved.
17
15.5 Swapping strings
• s1.swap(s2);– Switch contents of two strings
2003 Prentice Hall, Inc.All rights reserved.
Outline18
fig15_04.cpp(1 of 1)
1 // Fig. 15.4: fig15_04.cpp2 // Using the swap function to swap two strings.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <string>9 10 using std::string;11 12 int main()13 {14 string first( "one" ); 15 string second( "two" );16 17 // output strings18 cout << "Before swap:\n first: " << first19 << "\nsecond: " << second;20 21 first.swap( second ); // swap strings22 23 cout << "\n\nAfter swap:\n first: " << first24 << "\nsecond: " << second << endl;25 26 return 0;27 28 } // end main
Call swap.
2003 Prentice Hall, Inc.All rights reserved.
Outline19
fig15_04.cppoutput (1 of 1)
Before swap:
first: one
second: two
After swap:
first: two
second: one
2003 Prentice Hall, Inc. All rights reserved.
20
15.6 string Characteristics
• Member functions– s1.size() and s1.length()
• Number of characters in string
– s1.capacity()• Number of elements that can be stored without reallocation
– s1.max_size()• Maximum possible string size
– s1.empty() • Returns true if empty
– s1.resize(newlength)• Resizes string to newlength
2003 Prentice Hall, Inc.All rights reserved.
Outline21
fig15_05.cpp(1 of 3)
1 // Fig. 15.5: fig15_05.cpp2 // Demonstrating member functions related to size and capacity.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 using std::cin;8 using std::boolalpha;9 10 #include <string>11 12 using std::string;13 14 void printStatistics( const string & );15 16 int main()17 {18 string string1;19 20 cout << "Statistics before input:\n" << boolalpha;21 printStatistics( string1 );22 23 // read in "tomato"24 cout << "\n\nEnter a string: ";25 cin >> string1; // delimited by whitespace26 cout << "The string entered was: " << string1;
2003 Prentice Hall, Inc.All rights reserved.
Outline22
fig15_05.cpp(2 of 3)
27 28 cout << "\nStatistics after input:\n";29 printStatistics( string1 );30 31 // read in "soup"32 cin >> string1; // delimited by whitespace33 cout << "\n\nThe remaining string is: " << string1 << endl;34 printStatistics( string1 );35 36 // append 46 characters to string137 string1 += "1234567890abcdefghijklmnopqrstuvwxyz1234567890";38 cout << "\n\nstring1 is now: " << string1 << endl;39 printStatistics( string1 );40 41 // add 10 elements to string142 string1.resize( string1.length() + 10 );43 cout << "\n\nStats after resizing by (length + 10):\n";44 printStatistics( string1 );45 46 cout << endl;47 return 0;48 49 } // end main50
Resize string.
2003 Prentice Hall, Inc.All rights reserved.
Outline23
fig15_05.cpp(3 of 3)
fig15_05.cppoutput (1 of 2)
51 // display string statistics52 void printStatistics( const string &stringRef )53 {54 cout << "capacity: " << stringRef.capacity() 55 << "\nmax size: " << stringRef.max_size()56 << "\nsize: " << stringRef.size() 57 << "\nlength: " << stringRef.length() 58 << "\nempty: " << stringRef.empty(); 59 60 } // end printStatistics
Statistics before input:
capacity: 0
max size: 4294967293
size: 0
length: 0
empty: true
Enter a string: tomato soup
The string entered was: tomato
Statistics after input:
capacity: 31
max size: 4294967293
size: 6
length: 6
empty: false
Display various string characteristics.
2003 Prentice Hall, Inc.All rights reserved.
Outline24
fig15_05.cppoutput (2 of 2)
The remaining string is: soup
capacity: 31
max size: 4294967293
size: 4
length: 4
empty: false
string1 is now: soup1234567890abcdefghijklmnopqrstuvwxyz1234567890
capacity: 63
max size: 4294967293
size: 50
length: 50
empty: false
Stats after resizing by (length + 10):
capacity: 63
max size: 4294967293
size: 60
length: 60
empty: false
2003 Prentice Hall, Inc. All rights reserved.
25
15.7 Finding Strings and Characters in a string
• Find functions– If found, index returned
– If not found, string::npos returned• Public static constant in class string
– s1.find( s2 )– s1.rfind( s2 )
• Searches right-to-left
– s1.find_first_of( s2 )• Returns first occurrence of any character in s2• s1.find_frist_of( "abcd" )
– Returns index of first 'a', 'b', 'c' or 'd'
2003 Prentice Hall, Inc. All rights reserved.
26
15.7 Finding Strings and Characters in a string
• Find functions– s1.find_last_of( s2 )
• Finds last occurrence of any character in s2
– s1.find_first_not_of( s2 )• Finds first character NOT in s2
– s1.find_last_not_of( s2 )• Finds last character NOT in s2
2003 Prentice Hall, Inc.All rights reserved.
Outline27
fig15_06.cpp(1 of 3)
1 // Fig. 15.6: fig15_06.cpp2 // Demonstrating the string find member functions3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <string>9 10 using std::string;11 12 int main()13 {14 string string1( "noon is 12 p.m." );15 int location;16 17 // find "is" at location 518 cout << "Original string:\n" << string1 19 << "\n\n(find) \"is\" was found at: " 20 << string1.find( "is" ) 21 << "\n(rfind) \"is\" was found at: " 22 << string1.rfind( "is" );23 24 // find 'o' at location 125 location = string1.find_first_of( "misop" );
Find first occurrence of m, i, s, o or p.
Note call to function find.
2003 Prentice Hall, Inc.All rights reserved.
Outline28
fig15_06.cpp(2 of 3)
26 27 cout << "\n\n(find_first_of) found '" << string1[ location ]28 << "' from the group \"misop\" at: "29 << location;30 31 // find 'm' at location 1332 location = string1.find_last_of( "misop" );33 cout << "\n\n(find_last_of) found '" << string1[ location ] 34 << "' from the group \"misop\" at: "35 << location;36 37 // find '1' at location 8 38 location = string1.find_first_not_of( "noi spm" );39 cout << "\n\n(find_first_not_of) '" << string1[ location ]40 << "' is not contained in \"noi spm\" and was found at:" 41 << location;42 43 // find '.' at location 1244 location = string1.find_first_not_of( "12noi spm" );45 cout << "\n\n(find_first_not_of) '" << string1[ location ]46 << "' is not contained in \"12noi spm\" and was " 47 << "found at:" << location << endl;
Calls to other find functions similar.
2003 Prentice Hall, Inc.All rights reserved.
Outline29
fig15_06.cpp(3 of 3)
fig15_06.cppoutput (1 of 1)
48 49 // search for characters not in string150 location = string1.find_first_not_of( "noon is 12 p.m." );51 cout << "\nfind_first_not_of(\"noon is 12 p.m.\")" 52 << " returned: " << location << endl;53 54 return 0;55 56 } // end main
Original string:
noon is 12 p.m.
(find) "is" was found at: 5
(rfind) "is" was found at: 5
(find_first_of) found 'o' from the group "misop" at: 1
(find_last_of) found 'm' from the group "misop" at: 13
(find_first_not_of) '1' is not contained in "noi spm" and was found at:8
(find_first_not_of) '.' is not contained in "12noi spm" and was found at:12
find_first_not_of("noon is 12 p.m.") returned: -1
2003 Prentice Hall, Inc. All rights reserved.
30
15.8 Replacing Characters in a string
• s1.erase( start )– Erase from index start to end of string, including start
• Replace– s1.replace( begin, N, s2)
• begin: index in s1 to start replacing• N: number of characters to replace• s2: replacement string
– s1.replace( begin, N, s2, index, num )• index: element in s2 where replacement begins• num: number of elements to use when replacing
– Replacement can overwrite characters– string::npos represents max string length
2003 Prentice Hall, Inc.All rights reserved.
Outline31
fig15_07.cpp(1 of 2)
1 // Fig. 15.7: fig15_07.cpp2 // Demonstrating string member functions erase and replace.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <string>9 10 using std::string;11 12 int main()13 {14 // compiler concatenates all parts into one string15 string string1( "The values in any left subtree"16 "\nare less than the value in the"17 "\nparent node and the values in"18 "\nany right subtree are greater"19 "\nthan the value in the parent node" );20 21 cout << "Original string:\n" << string1 << endl << endl;22 23 // remove all characters from (and including) location 6224 // through the end of string1 25 string1.erase( 62 ); 26
2003 Prentice Hall, Inc.All rights reserved.
Outline32
fig15_07.cpp(2 of 2)
27 // output new string28 cout << "Original string after erase:\n" << string129 << "\n\nAfter first replacement:\n";30 31 // replace all spaces with period32 int position = string1.find( " " );33 34 while ( position != string::npos ) {35 string1.replace( position, 1, "." );36 position = string1.find( " ", position + 1 );37 } // end while38 39 cout << string1 << "\n\nAfter second replacement:\n";40 41 // replace all periods with two semicolons42 // NOTE: this will overwrite characters43 position = string1.find( "." );44 45 while ( position != string::npos ) {46 string1.replace( position, 2, "xxxxx;;yyy", 5, 2 );47 position = string1.find( ".", position + 1 );48 } // end while49 50 cout << string1 << endl;51 return 0;52 53 } // end main
Find each space and replace with a '.'
Start each search at the next position.
Replace all '.' with two semicolons (the two characters at index 5).
string::npos represents max string length.
2003 Prentice Hall, Inc.All rights reserved.
Outline33
fig15_07.cppoutput (1 of 1)
Original string:
The values in any left subtree
are less than the value in the
parent node and the values in
any right subtree are greater
than the value in the parent node
Original string after erase:
The values in any left subtree
are less than the value in the
After first replacement:
The.values.in.any.left.subtree
are.less.than.the.value.in.the
After second replacement:
The;;alues;;n;;ny;;eft;;ubtree
are;;ess;;han;;he;;alue;;n;;he
2003 Prentice Hall, Inc. All rights reserved.
34
15.9 Inserting Characters into a string
• s1.insert( index, s2 )– Inserts s2 before position index
• s1.insert( index, s2, index2, N );– Inserts substring of s2 before position index– Substring is N characters, starting at index2
2003 Prentice Hall, Inc.All rights reserved.
Outline35
fig15_08.cpp(1 of 2)
1 // Fig. 15.8: fig15_08.cpp2 // Demonstrating class string insert member functions.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <string>9 10 using std::string;11 12 int main()13 {14 string string1( "beginning end" );15 string string2( "middle " );16 string string3( "12345678" );17 string string4( "xx" );18 19 cout << "Initial strings:\nstring1: " << string120 << "\nstring2: " << string2 << "\nstring3: " << string321 << "\nstring4: " << string4 << "\n\n";22 23 // insert "middle" at location 10 in string124 string1.insert( 10, string2 ); 25
Insert all of string2 before element 10.
2003 Prentice Hall, Inc.All rights reserved.
Outline36
fig15_08.cpp(2 of 2)
fig15_08.cppoutput (1 of 1)
26 // insert "xx" at location 3 in string3 27 string3.insert( 3, string4, 0, string::npos );28 29 cout << "Strings after insert:\nstring1: " << string130 << "\nstring2: " << string2 << "\nstring3: " << string331 << "\nstring4: " << string4 << endl;32 33 return 0;34 35 } // end main
Initial strings:
string1: beginning end
string2: middle
string3: 12345678
string4: xx
Strings after insert:
string1: beginning middle end
string2: middle
string3: 123xx45678
string4: xx
Insert all of string4 before index 3.
2003 Prentice Hall, Inc. All rights reserved.
37
15.10 Conversion to C-Style char * Strings
• Conversion functions– strings not necessarily null-terminated– s1.copy( ptr, N, index )
• Copies N characters into the array ptr• Starts at location index• Need to null terminate
– s1.c_str()• Returns const char *• Null terminated
– s1.data()• Returns const char *• NOT null-terminated
2003 Prentice Hall, Inc.All rights reserved.
Outline38
fig15_09.cpp(1 of 2)
1 // Fig. 15.9: fig15_09.cpp2 // Converting to C-style strings.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <string>9 10 using std::string;11 12 int main()13 {14 string string1( "STRINGS" );15 const char *ptr1 = 0;16 int length = string1.length();17 char *ptr2 = new char[ length + 1 ]; // including null18 19 // copy characters from string1 into allocated memory20 string1.copy( ptr2, length, 0 );21 ptr2[ length ] = '\0'; // add null terminator22 23 // output 24 cout << "string s is " << string125 << "\nstring1 converted to a C-Style string is "26 << string1.c_str() << "\nptr1 is ";
Note calls to copy and c_str.
2003 Prentice Hall, Inc.All rights reserved.
Outline39
fig15_09.cpp(2 of 2)
fig15_09.cppoutput (1 of 1)
27 28 // Assign to pointer ptr1 the const char * returned by 29 // function data(). NOTE: this is a potentially dangerous30 // assignment. If string1 is modified, pointer ptr1 can 31 // become invalid. 32 ptr1 = string1.data(); 33 34 // output each character using pointer35 for ( int i = 0; i < length; i++ )36 cout << *( ptr1 + i ); // use pointer arithmetic37 38 cout << "\nptr2 is " << ptr2 << endl;39 delete [] ptr2;40 return 0;41 42 } // end main
string s is STRINGS
string1 converted to a C-Style string is STRINGS
ptr1 is STRINGS
ptr2 is STRINGS
2003 Prentice Hall, Inc. All rights reserved.
40
15.11 Iterators
• Iterators– Forwards and backwards traversal of strings
– Access to individual characters
– Similar to pointer operations
– More coverage Chapter 20
2003 Prentice Hall, Inc. All rights reserved.
41
15.11 Iterators
• Basic usage– Creation
• string::const_iterator i = s.begin();• const, cannot modify string (more Chapter 20)
– Referencing• *i; // reference character• ++i; // traverse one character forward
– Test for end of string• i != s.end()• end returns iterator after last element of s
2003 Prentice Hall, Inc.All rights reserved.
Outline42
fig15_10.cpp(1 of 1)
1 // Fig. 15.10: fig15_10.cpp2 // Using an iterator to output a string.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <string>9 10 using std::string;11 12 int main()13 {14 string string1( "Testing iterators" );15 string::const_iterator iterator1 = string1.begin();16 17 cout << "string1 = " << string118 << "\n(Using iterator iterator1) string1 is: ";19 20 // iterate through string 21 while ( iterator1 != string1.end() ) { 22 cout << *iterator1; // dereference iterator to get char23 ++iterator1; // advance iterator to next char 24 } // end while 25 26 cout << endl;27 return 0;28 29 } // end main
Print each character using the iterator.
2003 Prentice Hall, Inc.All rights reserved.
Outline43
fig15_10.cppoutput (1 of 1)
string1 = Testing iterators
(Using iterator iterator1) string1 is: Testing iterators
2003 Prentice Hall, Inc. All rights reserved.
44
15.12 String Stream Processing
• I/O of strings to and from memory– Called in-memory I/O or string stream processing
– Classes• istringstream (input from string)• ostringstream (output to a string)• <sstream> and <iostream> headers
– Use string formatting to save data to memory
2003 Prentice Hall, Inc. All rights reserved.
45
15.12 String Stream Processing
• String output– Ostringstream outputString;– outputString << s1 << s2;– Member function str
• Returns string that was output to memory• outputString.str()
2003 Prentice Hall, Inc.All rights reserved.
Outline46
fig15_11.cpp(1 of 2)
1 // Fig. 15.11: fig15_11.cpp2 // Using a dynamically allocated ostringstream object.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <string>9 10 using std::string;11 12 #include <sstream> 13 14 using std::ostringstream;15 16 int main()17 {18 ostringstream outputString; // create ostringstream instance19 20 string string1( "Output of several data types " );21 string string2( "to an ostringstream object:" );22 string string3( "\n double: " );23 string string4( "\n int: " );24 string string5( "\naddress of int: " );
Create ostringstream object.
2003 Prentice Hall, Inc.All rights reserved.
Outline47
fig15_11.cpp(2 of 2)
25 26 double double1 = 123.4567;27 int integer = 22;28 29 // output strings, double and int to outputString 30 outputString << string1 << string2 << string3 << double1 31 << string4 << integer << string5 << &integer;32 33 // call str to output contents 34 cout << "outputString contains:\n" << outputString.str();35 36 // add additional characters and call str to output string37 outputString << "\nmore characters added"; 38 cout << "\n\nafter additional stream insertions,\n"39 << "outputString contains:\n" << outputString.str() 40 << endl;41 42 return 0;43 44 } // end main
Output format just like to writing to cout.
2003 Prentice Hall, Inc.All rights reserved.
Outline48
fig15_11.cppoutput (1 of 1)
outputString contains:
Output of several data types to an ostringstream object:
double: 123.457
int: 22
address of int: 0012FE94
after additional stream insertions,
outputString contains:
Output of several data types to an ostringstream object:
double: 123.457
int: 22
address of int: 0012FE94
more characters added
2003 Prentice Hall, Inc. All rights reserved.
49
15.12 String Stream Processing
• String input– istringstream inputString ( myString );– inputString >> string1 >> string2– Like reading from cin
2003 Prentice Hall, Inc.All rights reserved.
Outline50
fig15_12.cpp(1 of 2)
1 // Fig. 15.12: fig15_12.cpp2 // Demonstrating input from an istringstream object.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <string>9 10 using std::string;11 12 #include <sstream>13 14 using std::istringstream;15 16 int main()17 {18 string input( "Input test 123 4.7 A" );19 istringstream inputString( input );20 string string1;21 string string2;22 int integer;23 double double1;24 char character;25
Create and initialize istringstream object.
2003 Prentice Hall, Inc.All rights reserved.
Outline51
fig15_12.cpp(2 of 2)
26 inputString >> string1 >> string2 >> integer >> double127 >> character; 28 29 cout << "The following items were extracted\n"30 << "from the istringstream object:"31 << "\nstring: " << string1 32 << "\nstring: " << string2 33 << "\n int: " << integer34 << "\ndouble: " << double135 << "\n char: " << character;36 37 // attempt to read from empty stream38 long value;39 40 inputString >> value;41 42 // test stream results43 if ( inputString.good() )44 cout << "\n\nlong value is: " << value << endl;45 else46 cout << "\n\ninputString is empty" << endl;47 48 return 0;49 50 } // end main
Read data into variables.
good returns 1 if can still read data (no EOF, bad bits, etc). In this case, there is no data, so the test fails.