作者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