140 likes | 272 Views
The Standard string Class. 8.2. C-strings require the programmer to keep track of the low level details of how they are stored in memory Lots of extra work A source of errors. string class. string class is defined in the <string> library
E N D
C-strings require the programmer to keep track of the low level details of how they are stored in memory • Lots of extra work • A source of errors
string class • string class is defined in the <string> library • This class allows us to treat string values and expressions much like values of a simple type • You can use the = operator for assignment • You can use the + operator for concatenation (with no danger of the resulting string being too small for its value)
constructors • Constructor – a function that allocates memory for an object • Default Constructor – a constructor that accepts no arguments that initializes data to some default value • Has a default constructor that initializes a string object to the empty string • Has a constructor that accepts one argument • Equivalent lines: • string noun(“ants”); • string noun = “ants”;
Conversions from C-string to string • Look at example 1 • Even though it may not be obvious, there are type conversions at work here • “I love “ is stored as a c-string • When C++ sees a c-string, the + operator, and a string, an automatic type conversion follows so that the operation can be performed
I/O with class string • You can use cout and << for output of string variables • You can use cin and >> for string input the same way you would with other data • Remember - >> skips initial whitespace and then stops reading when it encounters more whitespace • If you want your program to read an entire line of input into a variable of type string, you may use getline() • Syntax for use with type string is slightly different • Use cin as the first argument, the string variable as the second • You may want to use .get(), but remember this returns a char, NOT string – still can be useful • See example 2 and 3
Versions of getline() • getline(istream& cin, string& strVar)) • Stops reading when it encounters \n • getline(istream& cin, string& strVar, char delimeter) • Allows us to specify a different character as a stopping signal • You can use getline() in conjunction with >> but be careful • See example 4
Converting between string objects and C-Strings • See example 6