Strings in c++
- A string is a sequence of characters. C and C++ implement strings as arrays of char. The C++ language additionally supports string objects.
- In the C language, the only option is a char array.
- We use the term C string to refer to an array of characters as used in the C language. In this section, any mention of the term string refers to a C string.
- A string is an array of characters. A string literal is a sequence of characters enclosed within quotation marks, as in
std::cout << "How\n";
The string word can hold 255 viable characters plus the null terminator. If the user types in relatively short words (length less than 255 characters), there is no problem.
If at any time the user types in more characters than will fit in the word array, the executing program will have a problem.
The problem is known as a buffer overrun. In the best case, buffer overruns lead to buggy programs.
In the worst case, clever users can exploit buffer overruns to compromise software systems. Buffer overruns are always logic errors and you should take great care to avoid them.
Strings are arrays of characters. The special character ' \0' (NUL) is used to indicate the end of a string.
name = 'S';
name = 'a';
name = 'm';
name = '\0';
This creates a character array four elements long. Note that we had to allocate one character for the end-of-string marker.
String constants consist of text enclosed in double quotes ("). You may have already noticed that we've used string constants extensively for output with the cout standard class.
C++ does not allow one array to be assigned to another, so you can't write an assignment of the form:
name = "Sam"; // Illegal