[閒聊] string 的輸出

看板EE_DSnP作者 (Ric)時間14年前 (2009/10/20 15:05), 編輯推噓6(602)
留言8則, 7人參與, 最新討論串1/1
也許以為之前計程有教過, 所以沒有特別跟大家複習字串的輸出. 在此提醒一下: 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
原來char string可以直接cout...我都for它for一堆囧...
10/21 01:15, 2F

10/21 01:15, , 3F
真是慚愧= =...
10/21 01:15, 3F

10/21 08:12, , 4F
我也是一堆for XD
10/21 08:12, 4F

10/21 11:53, , 5F
剛剛上到 推一個XD
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
第十六行 buf[1] = 'e' 吧
10/21 17:05, 7F
※ 編輯: ric2k1 來自: 140.112.21.241 (10/21 17:14)

10/21 17:14, , 8F
哈哈, 已修正!
10/21 17:14, 8F
文章代碼(AID): #1AtM4hoo (EE_DSnP)