我正在测试“C++ Premiere”书中关于 C++ 中字符串的示例。
const int size = 9;
char name1[size];
char name2[size] = "C++owboy"; // 8 characters here
cout << "Howdy! I'm " << name2 << "! What's your name?" << endl;
cin >> name1; // I input "Qwertyuiop" - 11 chars. It is more than the size of name1 array;
// now I do cout
cout << "Well, your name has " << strlen(name1) << " letters"; // "Your name has 11 letters".
cout << " and is stored in an array of " << size(name1) << " bytes"; // ...stored in an array of 9 bytes.
11 个字符如何存储在一个数组中,仅用于 8 个字符 + '\0' 字符?编译时会变宽吗?还是字符串存储在其他地方?
另外,我不能这样做:
const int size = 9;
char name2[size] = "C++owboy_12345"; // assign 14 characters to 9 chars array
但可以做我上面写的:
cin >> name1; // any length string into an array of smaller size
这里的诀窍是什么?我使用 NetBeans 和 Cygwin g++ 编译器。