C++ Primer Plus P63——程序清单4.2
在数组中使用字符串
/*
C++ Primer Plus_程序清单4.2 P63
*/
#include<iostream>
#include<cstring>
int main(void)
{
using namespace std; //编译指令
const int Size = 15; //定义常整型,字符串的元素最大个数
char name1[Size];
char name2[Size] = "C++owboy"; //也可以:name2[Size] = {'C','+','+','O','W','B','O','Y','\0'}——也代表字符串
cout << "Howdy! I`m " << name2; //打印
cout << "! What`s your name" << endl;
cin >> name1;
cout << "Well, " << name1 << " , your name has ";
cout << strlen(name1) << "letter and is stored" << endl;
cout << "in an array of " << sizeof(name1) << " bytes." << endl; //返回显示名字在数组所占用的总字节数
cout << "Your initial is " << name1[0] << ".\n"; // 输出名字第一个元素
name2[3] = '\0'; //将数组name2的第3个元素作为该字符串的终止符
cout << "Here are the first 3 characters of my name: ";
cout << name2 << endl; //
return 0;
}
前置条件:
char name1[Size];
char name2[Size] = "C++owboy"; //也可以:name2[Size] = {'C','+','+','O','W','B','O','Y','\0'}——也代表字符串
核心运算:
cout << "Well, " << name1 << " , your name has ";
cout << strlen(name1) << "letter and is stored" << endl;
cout << "in an array of " << sizeof(name1) << " bytes." << endl; //返回显示名字在数组所占用的总字节数
cout << "Your initial is " << name1[0] << ".\n"; // 输出名字第一个元素
感谢观看
再次感谢~