You are on page 1of 52

Chapter 15 - Class string and String Stream Processing

Outline 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 15.9 15.10 15.11 15.12 Introduction string Assignment and Concatenation Comparing strings Substrings Swapping strings string Characteristics Finding Strings and Characters in a string Replacing Characters in a string Inserting Characters into a string Conversion to C-Style char * Strings Iterators String Stream Processing

2003 Prentice Hall, Inc. All rights reserved.

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.

15.1 Introduction No conversion from int or char


The following definitions are errors
string string string string error1 = 'c'; error2( 'u' ); error3 = 22; error4( 8 );

However, can assign to one char if declared


s = 'n';

2003 Prentice Hall, Inc. All rights reserved.

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.

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.

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

// Fig. 15.1: fig15_01.cpp // Demonstrating string assignment and concatenation. #include <iostream> using std::cout; using std::endl; #include <string>

Outline
fig15_01.cpp (1 of 3)

using std::string;
int main() { string string1( "cat" ); string string2; string string3;

String initialization and assignment.

Output string1: cat string2: cat string3: cat string2 = string1; // assign string1 to string2 string3.assign( string1 ); // assign string1 to string3 cout << "string1: " << string1 << "\nstring2: " << string2 << "\nstring3: " << string3 << "\n\n";

2003 Prentice Hall, Inc.


All rights reserved.

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

// modify string2 and string3 string2[ 0 ] = string3[ 2 ] = 'r'; cout << "After modification of string2 and string3:\n" << "string1: " << string1 << "\nstring2: " << string2 << "\nstring3: ";

Outline
fig15_01.cpp (2 of 3)

// demonstrating member function at After modification of string2 and string3: for ( int i = 0; i < string3.length(); string1: i++ ) cat cout << string3.at( i ); string2: rat string3: car // declare string4 and string5 string string4( string1 + "apult" ); Note use of member function string string5;

at instead of [].

// overloaded += string3 += "pet"; string1.append( "acomb" );

After concatenation: string1: catacomb string2: rat // append subscript locations 4 through end of string1 string3: to carpet // create string "comb" (string5 was initially empty) string4: catapult string5.append( string1, 4, string1.length() ); string5: comb cout << << << << "\n\nAfter concatenation:\nstring1: " << string1 "\nstring2: " << string2 << "\nstring3: " string3 << "\nstring4: " << string4 "\nstring5: " << string5 << endl;

// create "carpet" // create "catacomb"

2003 Prentice Hall, Inc.


All rights reserved.

51 52 53

return 0; } // end main

Outline
fig15_01.cpp (3 of 3) fig15_01.cpp output (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

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

// Fig. 15.2: fig15_02.cpp // Demonstrating string comparison capabilities. #include <iostream> using std::cout; using std::endl; #include <string>

11

Outline
fig15_02.cpp (1 of 4)

using std::string;
int main() { string string1( string string2( string string3( string string4(

"Testing the comparison functions." ); "Hello" ); "stinger" ); string2 );

2003 Prentice Hall, Inc.


All rights reserved.

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

cout << "string1: " << string1 << "\nstring2: " << string2 << "\nstring3: " << string3 << "\nstring4: " << string4 << "\n\n"; // comparing string1 and string4 if ( string1 == string4 ) cout << "string1 == string4\n"; else { // string1 != string4 if ( string1 > string4 ) cout << "string1 > string4\n"; else // string1 < string4 cout << "string1 < string4\n"; } // comparing string1 and string2 int result = string1.compare( string2 ); if ( result == 0 ) cout << "string1.compare( string2 ) == 0\n"; else // result != 0 if ( result > 0 ) cout << "string1.compare( string2 ) > 0\n"; else // result < 0 cout << "string1.compare( string2 ) < 0\n";

12

Outline
fig15_02.cpp (2 of 4)

Note use of overloaded == operator.


string1: string2: string3: string4:

Testing the comparison functions. Hello stinger Hello

string1 > string4

2003 Prentice Hall, Inc.


All rights reserved.

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

// comparing string1 (elements 2-5) and string3 (elements 0-5) result = string1.compare( 2, 5, string3, 0, 5 ); if ( result == 0 ) cout << "string1.compare( 2, 5, string3, 0, 5 ) == 0\n"; else // result != 0 if ( result > 0 ) cout << "string1.compare( 2, 5, string3, 0, 5 ) > 0\n"; else // result < 0 cout << "string1.compare( 2, 5, string3, 0, 5 ) < 0\n"; // comparing string2 and string4 result = string4.compare( 0, string2.length(), string2 ); if ( result == 0 ) cout << "string4.compare( 0, string2.length(), " << "string2 ) == 0" << endl; else // result != 0 if ( result > 0 ) cout << "string4.compare( 0, string2.length(), " << "string2 ) > 0" << endl; else // result < 0 cout << "string4.compare( 0, string2.length(), " << "string2 ) < 0" << endl;

13

Outline
fig15_02.cpp (3 of 4)

Note use of compare.

2003 Prentice Hall, Inc.


All rights reserved.

69 70 71 72 73 74 75 76 77 78 79 80 81 82

// comparing string2 and string4 result = string2.compare( 0, 3, string4 ); if ( result == 0 ) cout << "string2.compare( 0, 3, string4 ) == 0" << endl; else // result != 0 if ( result > 0 ) cout << "string2.compare( 0, 3, string4 ) > 0" << endl; else // result < 0 cout << "string2.compare( 0, 3, string4 ) < 0" << endl; return 0; } // end main Testing the comparison functions. Hello stinger Hello

14

Outline
fig15_02.cpp (4 of 4) fig15_02.cpp output (1 of 1)

string1: string2: string3: string4:

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

// Fig. 15.3: fig15_03.cpp // Demonstrating string member function substr. #include <iostream> using std::cout; using std::endl; #include <string>

16

Outline
fig15_03.cpp (1 of 1) fig15_03.cpp output (1 of 1)

using std::string;
int main() { string string1( "The airplane landed on time." ); // retrieve substring "plane" which // begins at subscript 7 and consists of 5 elements cout << string1.substr( 7, 5 ) << endl; return 0; } // end main

Note usage of substr.

plane

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

// Fig. 15.4: fig15_04.cpp // Using the swap function to swap two strings. #include <iostream> using std::cout; using std::endl; #include <string>

18

Outline
fig15_04.cpp (1 of 1)

using std::string;
int main() { string first( "one" ); string second( "two" ); // output strings Call swap. cout << "Before swap:\n first: " << first << "\nsecond: " << second; first.swap( second ); // swap strings

cout << "\n\nAfter swap:\n first: " << first << "\nsecond: " << second << endl;
return 0; } // end main

2003 Prentice Hall, Inc.


All rights reserved.

Before swap: first: one second: two After swap: first: two second: one

19

Outline
fig15_04.cpp output (1 of 1)

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

// Fig. 15.5: fig15_05.cpp // Demonstrating member functions related to size and capacity. #include <iostream> using using using using std::cout; std::endl; std::cin; std::boolalpha;

21

Outline
fig15_05.cpp (1 of 3)

#include <string>
using std::string; void printStatistics( const string & ); int main() { string string1; cout << "Statistics before input:\n" << boolalpha; printStatistics( string1 );

// read in "tomato" cout << "\n\nEnter a string: "; cin >> string1; // delimited by whitespace cout << "The string entered was: " << string1;

2003 Prentice Hall, Inc.


All rights reserved.

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

22
cout << "\nStatistics after input:\n"; printStatistics( string1 ); // read in "soup" cin >> string1; // delimited by whitespace cout << "\n\nThe remaining string is: " << string1 << endl; printStatistics( string1 );

Outline
fig15_05.cpp (2 of 3)

// append 46 characters to string1 string1 += "1234567890abcdefghijklmnopqrstuvwxyz1234567890"; cout << "\n\nstring1 is now: " << string1 << endl; Resize string. printStatistics( string1 );
// add 10 elements to string1 string1.resize( string1.length() + 10 ); cout << "\n\nStats after resizing by (length + 10):\n"; printStatistics( string1 ); cout << endl; return 0;

// end main

2003 Prentice Hall, Inc.


All rights reserved.

51 52 53 54 55 56 57 58 59 60

// display string statistics void printStatistics( const string &stringRef ) { cout << "capacity: " << stringRef.capacity() << "\nmax size: " << stringRef.max_size() << "\nsize: " << stringRef.size() << "\nlength: " << stringRef.length() << "\nempty: " << stringRef.empty();

Display various string Outline characteristics. fig15_05.cpp (3 of 3) fig15_05.cpp output (1 of 2)

23

// 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

2003 Prentice Hall, Inc.


All rights reserved.

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

24

Outline
fig15_05.cpp output (2 of 2)

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

// Fig. 15.6: fig15_06.cpp // Demonstrating the string find member functions #include <iostream> using std::cout; using std::endl; #include <string>

27

Outline
fig15_06.cpp (1 of 3)

using std::string;
int main() { string string1( "noon is 12 p.m." ); int location; // find cout << << << << << "is" at location 5 "Original string:\n" << string1 "\n\n(find) \"is\" was found at: " string1.find( "is" ) "\n(rfind) \"is\" was found at: " string1.rfind( "is" );

Note call to function find.

Find first occurrence of m, i, s, o or p.

// find 'o' at location 1 location = string1.find_first_of( "misop" );

2003 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

28
cout << "\n\n(find_first_of) found '" << string1[ location ] << "' from the group \"misop\" at: " Calls to other find << location;

Outline
functions fig15_06.cpp (2 of 3)

similar.
// find 'm' at location 13 location = string1.find_last_of( "misop" ); cout << "\n\n(find_last_of) found '" << string1[ location ] << "' from the group \"misop\" at: " << location; // find '1' at location 8 location = string1.find_first_not_of( "noi spm" ); cout << "\n\n(find_first_not_of) '" << string1[ location ] << "' is not contained in \"noi spm\" and was found at:" << location; // find '.' at location 12 location = string1.find_first_not_of( "12noi spm" ); cout << "\n\n(find_first_not_of) '" << string1[ location ] << "' is not contained in \"12noi spm\" and was " << "found at:" << location << endl;

2003 Prentice Hall, Inc.


All rights reserved.

48 49 50 51 52 53 54 55 56

29
// search for characters not in string1 location = string1.find_first_not_of( "noon is 12 p.m." ); cout << "\nfind_first_not_of(\"noon is 12 p.m.\")" << " returned: " << location << endl; return 0; } // end main

Outline
fig15_06.cpp (3 of 3) fig15_06.cpp output (1 of 1)

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

// Fig. 15.7: fig15_07.cpp // Demonstrating string member functions erase and replace. #include <iostream> using std::cout; using std::endl; #include <string>

31

Outline
fig15_07.cpp (1 of 2)

using std::string;
int main() { // compiler concatenates all parts into one string string string1( "The values in any left subtree" "\nare less than the value in the" "\nparent node and the values in" "\nany right subtree are greater" "\nthan the value in the parent node" ); cout << "Original string:\n" << string1 << endl << endl;

// remove all characters from (and including) location 62 // through the end of string1 string1.erase( 62 );

2003 Prentice Hall, Inc.


All rights reserved.

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

// output new string string::npos represents cout << "Original string after erase:\n" << string1 max string length. << "\n\nAfter first replacement:\n"; // replace all spaces with period int position = string1.find( " " ); while ( position != string::npos ) { string1.replace( position, 1, "." ); position = string1.find( " ", position + 1 ); } // end while cout << string1 << "\n\nAfter second replacement:\n"; // replace all periods with two semicolons // NOTE: this will overwrite characters position = string1.find( "." );

32

Outline

fig15_07.cpp Find each space and (2replace of 2) with a '.'

Start each search at the next position.

while ( position != string::npos ) { string1.replace( position, 2, "xxxxx;;yyy", 5, 2 ); position = string1.find( ".", position + 1 ); } // end while cout << string1 << endl; return 0; } // end main

Replace all '.' with two semicolons (the two characters at index 5).

2003 Prentice Hall, Inc.


All rights reserved.

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

33

Outline
fig15_07.cpp output (1 of 1)

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

// Fig. 15.8: fig15_08.cpp // Demonstrating class string insert member functions. #include <iostream> using std::cout; using std::endl; #include <string>

35

Outline
fig15_08.cpp (1 of 2)

using std::string;
int main() { string string1( string string2( string string3( string string4(

"beginning end" ); "middle " ); "12345678" ); "xx" );

cout << "Initial strings:\nstring1: " << string1 << "\nstring2: " << string2 << "\nstring3: " << string3 Insert all of string2 << "\nstring4: " << string4 << "\n\n";

before

element 10.

// insert "middle" at location 10 in string1 string1.insert( 10, string2 );

2003 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33 34 35

// insert "xx" at location 3 in string3 string3.insert( 3, string4, 0, string::npos ); cout << "Strings after insert:\nstring1: " << string1 << "\nstring2: " << string2 << "\nstring3: " << string3 << "\nstring4: " << string4 << endl; return 0;

36

Outline
fig15_08.cpp (2 of 2) fig15_08.cpp output (1 of 1)

Insert all of string4 before index 3.

// 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

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

// Fig. 15.9: fig15_09.cpp // Converting to C-style strings. #include <iostream> using std::cout; using std::endl; #include <string>

38

Outline
fig15_09.cpp (1 of 2)

using std::string;
int main() { Note calls to copy and string string1( "STRINGS" ); c_str. const char *ptr1 = 0; int length = string1.length(); char *ptr2 = new char[ length + 1 ]; // including null // copy characters from string1 into allocated memory string1.copy( ptr2, length, 0 ); ptr2[ length ] = '\0'; // add null terminator

// output cout << "string s is " << string1 << "\nstring1 converted to a C-Style string is " << string1.c_str() << "\nptr1 is ";

2003 Prentice Hall, Inc.


All rights reserved.

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

39
// Assign to pointer ptr1 the const char * returned by // function data(). NOTE: this is a potentially dangerous // assignment. If string1 is modified, pointer ptr1 can // become invalid. ptr1 = string1.data(); // output each character using pointer for ( int i = 0; i < length; i++ ) cout << *( ptr1 + i ); // use pointer arithmetic cout << "\nptr2 is " << ptr2 << endl; delete [] ptr2; return 0; } // end main

Outline
fig15_09.cpp (2 of 2) fig15_09.cpp output (1 of 1)

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

// Fig. 15.10: fig15_10.cpp // Using an iterator to output a string. #include <iostream> using std::cout; using std::endl; #include <string>

42

Outline
fig15_10.cpp (1 of 1)

using std::string;
int main() { string string1( "Testing iterators" ); string::const_iterator iterator1 = string1.begin(); cout << "string1 = " << string1 Print each << "\n(Using iterator iterator1) string1 is: ";

character using the

iterator.

// iterate through string while ( iterator1 != string1.end() ) { cout << *iterator1; // dereference iterator to get char ++iterator1; // advance iterator to next char } // end while cout << endl; return 0; } // end main

2003 Prentice Hall, Inc.


All rights reserved.

string1 = Testing iterators (Using iterator iterator1) string1 is: Testing iterators

43

Outline
fig15_10.cpp output (1 of 1)

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

// Fig. 15.11: fig15_11.cpp // Using a dynamically allocated ostringstream object. #include <iostream> using std::cout; using std::endl; #include <string>

46

Outline
fig15_11.cpp (1 of 2)

using std::string;
#include <sstream> using std::ostringstream; int main() { ostringstream outputString; string string string string string string1( string2( string3( string4( string5(

Create ostringstream object.


// create ostringstream instance

"Output of several data types " ); "to an ostringstream object:" ); "\n double: " ); "\n int: " ); "\naddress of int: " );

2003 Prentice Hall, Inc.


All rights reserved.

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

47
double double1 = 123.4567; int integer = 22; // output strings, double and int to outputString outputString << string1 << string2 << string3 << double1 << string4 << integer << string5 << &integer; // call str to output contents cout << "outputString contains:\n" << outputString.str(); // add additional characters and call str to output string outputString << "\nmore characters added"; Output format just like to cout << "\n\nafter additional stream insertions,\n" writing to cout. << "outputString contains:\n" << outputString.str() << endl; return 0; } // end main

Outline
fig15_11.cpp (2 of 2)

2003 Prentice Hall, Inc.


All rights reserved.

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

48

Outline
fig15_11.cpp output (1 of 1)

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

// Fig. 15.12: fig15_12.cpp // Demonstrating input from an istringstream object. #include <iostream> using std::cout; using std::endl; #include <string>

50

Outline
fig15_12.cpp (1 of 2)

using std::string;
#include <sstream> using std::istringstream; int main() { string input( "Input test 123 4.7 A" ); istringstream inputString( input ); string string1; string string2; int integer; double double1; char character;

Create and initialize istringstream object.

2003 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

inputString >> string1 >> string2 >> integer >> double1 >> character; cout << << << << << << << "The following items were extracted\n" "from the istringstream object:" "\nstring: " << string1 Read data into "\nstring: " << string2 "\n int: " << integer "\ndouble: " << double1 "\n char: " << character;

51

Outline
fig15_12.cpp (2 of 2)

variables.

// attempt to read from empty stream long value; inputString >> value;

// test stream results if ( inputString.good() ) cout << "\n\nlong value is: " << value << endl; else cout << "\n\ninputString is empty" << endl;

good returns 1 if can still read data (no EOF, bad bits, etc). In this case, there is no data, so the test fails.

return 0;
} // end main

2003 Prentice Hall, Inc.


All rights reserved.

The following items were extracted from the istringstream object: string: Input string: test int: 123 double: 4.7 char: A inputString is empty

52

Outline
fig15_12.cpp output (1 of 1)

2003 Prentice Hall, Inc.


All rights reserved.

You might also like