作者ric2k1 (Ric)
看板EE_DSnP
標題[閒聊] string 的輸出
時間Tue Oct 20 15:05:12 2009
也許以為之前計程有教過, 所以沒有特別跟大家複習字串的輸出.
在此提醒一下:
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
1F:推 flax00298:基本觀念推 10/20 22:34
2F:推 a3785lexx:原來char string可以直接cout...我都for它for一堆囧... 10/21 01:15
3F:→ a3785lexx:真是慚愧= =... 10/21 01:15
4F:推 dryman:我也是一堆for XD 10/21 08:12
5F:推 angelicdream:剛剛上到 推一個XD 10/21 11:53
6F:推 bigheadcooL:推 10/21 11:55
※ 編輯: ric2k1 來自: 140.112.21.241 (10/21 16:44)
7F:推 hrs113355:第十六行 buf[1] = 'e' 吧 10/21 17:05
※ 編輯: ric2k1 來自: 140.112.21.241 (10/21 17:14)
8F:→ ric2k1:哈哈, 已修正! 10/21 17:14