I got to know something about C++ when learning CS106X-Stanford and Object-Oriented Programming-Zhejiang University . However, I haven’t learned C++ specially. In this summer vacation, I will dig into C++ and keep notes here.
Ways to initialize a
string s1; // Default initialization; s1 is the empty string.
string s2(s1); // s2 is a copy of s1.
string s2 = s1; // Equivalent to s2(s1), s2 is a copy of s1.
string s3("value"); // s3 is a copy of the string literal, not including the null.
string s3 = "value"; // Equivalent to s3("value"), s3 is a copy ofo the string literal.
string s4(n, 'c'); // Initialize s4 with n copies of the character 'c'.
copy initialize: initialize a variable using
direct initialize: omit the
string input operator (
is >> s) reads and discards any leading whitespace (e.g., spaces, newlines, tabs). It then reads characters until the next whitespace character is encountered.
getline(is, s) reads a line of input from
s. This function reads the given stream up to and including the first newline and stores what it read - not including the newline - in its
size returns a
string::size_type value. It is an unsigned type. Try to avoid problems due to conversion between
int by not using
ints in expressions that use
Adding Literals and strings
For historical reasons, and for compatibility with C, string literals are not standard library
strings. It is important to remember that these types differ when you use string literals and library
When we mix
strings and string or character literals, at least one operand to each
+ operator must be of
string type. Thus, it is illegal to add two string literals. (
error: invalid operands to binary expression ('const char *' and 'const char *'))
!= rather than
Use iterators rather than subscripts.