原完整教程链接:6.6 C-style strings
1.
/*
A C-style string is simply an array of characters that uses a null
terminator. A null terminator is a special character (‘\0’, ascii code 0)
used to indicate the end of the string. More generically, A C-style
string is called a null-terminated string.
When printing a C-style string, std::cout prints characters until it
encounters the null terminator. If you accidentally overwrite the
null terminator in a string (e.g. by assigning something to
mystring[6]), you’ll not only get all the characters in the string, but
std::cout will just keep printing everything in adjacent memory
slots until it happens to hit a 0!
*/
/*
Although “string” only has 6 letters, C++ automatically adds a null
terminator to the end of the string for us (we don’t need to include
it ourselves). Consequently, mystring is actually an array of length 7!
*/
char mystring[] = "string";
2.
// The recommended way of reading strings using cin is as follows:
/*
This call to cin.getline() will read up to 254 characters into name
(leaving room for the null terminator!). Any excess characters will
be discarded. In this way, we guarantee that we will not overflow the array!
*/
#include <iostream>
int main()
{
char name[255]; // declare array large enough to hold 255 characters
std::cout << "Enter your name: ";
std::cin.getline(name, 255);
std::cout << "You entered: " << name << '\n';
return 0;
}
3.
// Don’t use C-style strings, use std::string (defined in the <string>
// header) instead.