/* programNo4.2 */
/***********************************
2017年9月27日11:07:54
Athor:xiyuan255
Course:C++
Contain:string.cpp
Reference: C++ Primer plus
知识点:
1.C风格的字符串:以空字符(null character)结尾,空字符被写作\0,其ASCII码为0;
用来标记字符串的结尾;
char dog[8] = {'b', 'e', 'a', 'u', 'x', ' ', 'I', 'I'}; // not string
char cat[8] = {'f', 'a', 't', 'e', 's', 's', 'a', '\0'}; //a string
2.sizeof运算符指出的是整个数组的长度;但strlen()函数返回的是存储在数组中字符串
的长度,而不是数组本身的长度;
3.另外strlen()只计算可见字符,不把空字符计算在内。但数组存储字符串时,数据长度
不能短于strlen()+1;因为'\0'字符也需要存储在数组中;
*************************************/
// string.cpp -- storing string in an array
#include <iostream>
#include <cstring> // for the strlen() function
int main(void)
{
using namespace std;
const int Size = {15};
char name1[Size]; // empty array
char name2[Size] = "C++owboy"; // initialized array
// NOTE: some implementations may require the static
// to initialize the array name2
cout << "Howdy! I'm " << name2;
cout << " what's yours 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 null character
cout << "Here are the first 3 characters of my name: ";
cout << name2 << endl;
return 0;
}
/**
输出结果:
Howdy! I'm C++owboy what's yours name?
Basicman
Well Basicman your name has 8 letters and is stored
in an array of 15 bytes.
Your initial is B.
Here are the first 3 characters of my name: C++
*/