Similar presentations

2
HL1 In C-language a character array with terminating zero is used as a string. C-library contains many string manipulation functions (string.h). There are many disadvantages in C-like strings: They can not be assigned with assignment operator. They can not be compared wit comparison operators. They cannot expand automatically, to mention some of the drawbacks. Now when we have learned basics of classes, we would be able to define a class string for example in the following way and implement its operation functions: class string { public: string(const char *string0=“”); string operator+(const string &s2) const; const string &operator=(const string &right); //and many other operators and member // functions private: char *c_string; }; But it is not necessary to implement it ourselves, because it is done in C++ standard library. We only have to include the header file and use it. #include Class string

7
HL6 Allocation policy As we saw in the previous page, the size (length) of the string can be different from the capacity. The memory allocation policy can be different in different systems but the following example gives an idea of how it could work (this is the case in DevCpp). Example. Size CapacityContents string s; // 00Empty s = “abcd”;// 44|abcd| s.reserve(8);// 48|abcd| s = s + “efg”;// 78|abcdefg| s = s + “hij”;// 1010|abcdefghij| s.resize(14);// 1414|abcdefghij □□□□ | s.reserve(20);// 1420|abcdefghij □□□□ | s.resize(17)// 1720|abcdefghij □□□□□□□ | □ represents a space in the example above

10
HL9 String streams We have used input streams to read information from the keyboard and output streams to display information. Input streams and output stream make conversions as we see in the following example int a = 127; double b; cout << a; // conversion is done from int to chars cin >> b; // conversion is done from chars to double When we write (<>) information from the stream it comes from the keyboard. In the lab exercises 5 we saw that we can connect a stream to the disk file. It is also possible to specify a stream that contains a string. In this case when we write data to the stream it goes to the string and when we read the stream, data comes from the string. This is useful when we need to make conversions. See an example program in the following page.

11
HL10 String streams example // This program demonstrates how to use string // streams to make conversions from numbers to // strings and vice versa int main() { // Convert a number to string string num_str; int num_int = 127; ostringstream string_stream; string_stream << num_int; num_str =string_stream.str(); // now we have it // as a string // Convert a string to the number string num_str(“127”); int num_int; istringstream string_stream(num_str); string_stream >> num_int; // now we have it // as int }