提示
要将字符串存储到数组中,最常用的方法有两种。
- 将数组初始化为字符串常量
- 将键盘或文件输入 读入到数组中。
代码&注释
// strings.cpp -- storing strings in an array
#include <iostream>
#include <cstring> // for the strlen() function
int main() {
using namespace std;
const int Size = 15;
char name1[Size]; // empty arrary
char name2[Size] = "C++owboy"; // initialized array
cout << "Howdy! I'm " << name2;
cout << "! What's your name?\n";
cin >> name1;
cout << "Well, " << name1 << ", your name has ";
cout << strlen(name1) << " letters and is stored\n";
cout << "in an array of " << sizeof(name1) << " bytes.\n";
cout << "Your initial is " << name1[0] << ".\n";
name2[3] = '\0'; // set to null character
cout << "Here are the first 3 characters of my name: ";
cout << name2 << endl;
return 0;
}
小结一下
sizeof 运算符能指出整个数组的长度:15 字节。
strlen() 只计算可见的字符。
这里还用到了 符号常量 const int Size = 15;
存储的字符串的最后一位是不可见的 \0