[閒聊] string 的輸出
也許以為之前計程有教過, 所以沒有特別跟大家複習字串的輸出.
在此提醒一下:
1. 所謂字串, 就是 char string, 就是 char array with '\0' at the end.
So you can have:
char buf[80] = "Hello";
==> buf[0] = 'H'; buf[1] = 'e'... buf[5] = 0; // '\0' 表示 ASCII = 0
==> buf[5] = 0 是自動被放入的.
2. 既然是 char array, 你可以宣告一個 char pointer 去指到這個 array.
So you can do:
char *ptr = buf;
==> *ptr = 'H';
And if you do:
ptr += 4;
==> *ptr = 'o';
3. To print a char string, just cout the array or the pointer.
So you should do:
cout << buf;
or
cout << ptr;
The above printing will continue until a '\0' is seen.
In other words, if you forget to put an '\0' at the end, you will see some
亂碼 after your string.
4. Of course, you can change the pointer to point to anywhere in the
string, and cout will print out the string from there.
So if you do:
ptr = buf;
++ptr;
buf[4] = 0; // 10/21 修正
cout << ptr; // 10/21 修正
You will see "ell".
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.21.241
推
10/20 22:34, , 1F
10/20 22:34, 1F
推
10/21 01:15, , 2F
10/21 01:15, 2F
→
10/21 01:15, , 3F
10/21 01:15, 3F
推
10/21 08:12, , 4F
10/21 08:12, 4F
推
10/21 11:53, , 5F
10/21 11:53, 5F
推
10/21 11:55, , 6F
10/21 11:55, 6F
※ 編輯: ric2k1 來自: 140.112.21.241 (10/21 16:44)
推
10/21 17:05, , 7F
10/21 17:05, 7F
※ 編輯: ric2k1 來自: 140.112.21.241 (10/21 17:14)
→
10/21 17:14, , 8F
10/21 17:14, 8F