[問題] 字串分開實作

作者: wtchen (沒有存在感的人)   2015-06-12 16:53:22
問題(Question):
正在想一個實作問題:如何將一個長的字串char*按照分隔符號(\t)分成幾個char*
舉例:某文字檔有長字串如下:
Number (\t) First Name (\t) Last Name (\t) Points (\t) Flavor (\n)
1 (\t) Eve (\t) Jackson (\t) 94 (\t) 3.45 (\n)
2 (\t) John (\t) Doe (\t) 80 (\t) 9.21 (\n)
3 (\t) Adam (\t) Johnson (\t) 67 (\t) 4.80 (\n)
4 (\t) Jill (\t) Smith (\t) 50 (\t) 2.22 (\n)
然後我設兩個pointer, char *line 跟 char **t(sizeof(char*)*MAXITEM)
我用fgets(line,SIZE,fp);把字串一行一行載入line後,把\t跟換成\0,
再把line的\0位置address轉給t
以第1行為例:
t[0] = line, t[0] = (char*)malloc(6-0+1) -> *t[0] = "Number\0" ?
t[1] = line+7, t[1] = (char*)malloc(17-7+1) -> *t[1] = "First Name\0" ?
t[2] = line+18, t[2] = (char*)malloc(27-18+1) -> *t[2] = "Last Name\0" ?
t[3] = line+28, t[3] = (char*)malloc(34-28+1) -> *t[3] = "Point\0" ?
t[4] = line+35, t[4] = (char*)malloc(41-35+1) -> *t[4] = "Flavor\n" ?
用這種方法載入第2行,第3行後,我就能用atoi或atof把某些t[i]轉成數字。
但是我不太懂要怎麼把**t跟*line設在同一address上
還有程式跑完我要free的話,兩個adress重疊會不會出問題?
還是板友有更好的方法可以建議?
我是希望能儘可能用效率高的方法(而且是用C的語法)
希望各位能理解我想做的東西。
謝謝
作者: Feis (永遠睡不著 @@)   2015-06-12 17:11:00
不知道你想幹嘛,把\t換\0後生個指標陣列指一指就好
作者: fireslayer (fireslayer)   2015-06-12 17:13:00
你是不是在找 Strtok?
作者: wtchen (沒有存在感的人)   2015-06-12 17:22:00
strtok我知道,可是那不是我想要的還是遇到atoi遇到\0會自動停下來?
作者: MOONRAKER (㊣牛鶴鰻毛人)   2015-06-12 18:05:00
你知道atoi()的參數是C String嗎
作者: bibo9901 (function(){})()   2015-06-12 18:17:00
你要的看起來就是strtok啊
作者: lj0113 (tiny legend)   2015-06-12 20:38:00
2F說的對, newPtr = strtok( s1, " \n" );s1會被strtok拿去弄, 所以不可以宣告為constant string
作者: arthur104 (arthur)   2015-06-12 22:03:00
free(t[i])會出事吧

Links booklink

Contact Us: admin [ a t ] ucptt.com