/*
4.字符串
xaye , 夏夜
C:char[] , char*
C++:string
*/
#include<iostream>
using namespace std;
int main() {
// xaye , 夏夜
char name[4] = {'x','a','y','e'};
cout << "我的名字是:" << name << endl;
return 0;
}
xaye@orange:~/code/dev/9$ ./a.out
我的名字是:xaye
#include<iostream>
using namespace std;
int main() {
// 【下面四種寫法 效果一致】
// xaye , 夏夜
//char name[4] = {'x','a','y','e','\0'};
// 這種定義需要注意後面主動加 \0 ,測試中沒加好像也正常?
//char name[] = {'x','a','y','e','\0'};
// error: initializer-string for ‘char [4]’ is too long [-fpermissive]
// 18 | char name[4] = "xaye";
// 這種要多一個位置 給 \0,不然報錯!
//char name[4] = "xaye";
char name[] = "xaye";
cout << "我的名字是:" << name << endl;
return 0;
}
#include<iostream>
#include<cstring> // 要導入的頭文件
using namespace std;
int main() {
// xaye , 夏夜
const int SIZE = 15;
char name1[SIZE];
char name2[SIZE] = "C++owboy";
cout << "Howdy! I'm " << name2 << "! what your name?" << endl;
cin >> name1;
// strlen: 獲取字符串的長度,也是跟我們之前説的一樣 \0 結尾
cout << "Well, " << name1 << ", your name has " << strlen(name1) << " letters and is stored" << endl;
cout << "in an array of " << sizeof(name1) << " bytes." << endl;
cout << "Your inital is " << name1[0] << endl;
name2[3] = '\0';
cout << "Here are the first 3 chacters of my name: " << name2 << endl;
cout << "name2 has " << strlen(name2) << " letters." << endl;
return 0;
}
xaye@orange:~/code/dev/9$ ./a.out
Howdy! I'm C++owboy! what your name?
xaye
Well, xaye, your name has 4 letters and is stored
in an array of 15 bytes.
Your inital is x
Here are the first 3 chacters of my name: C++
name2 has 3 letters.
讀到 \0 就不去讀了,它是中止符!