只是爲了它的樂趣,我正在編寫一個程序,它將接收用戶輸入的字符串(或者甚至可能是文本文檔)並對字符串中的單詞進行加擾。strtok的更清潔的實現
我試圖使用strtok
函數來分隔字符串中的每個單詞。目前,我覺得我目前執行的strtok
是馬虎:
int main(int argc, char *argv[])
{
char *string, *word;
if(!(string = getstr())) //function I wrote to retrieve a string
{
fputs("Error.\n", stderr);
exit(1);
}
char array[strlen(string) + 1]; //declare an array sized to the length of the string
strcpy(array, string); //copy the string into the array
free(string);
if(word = strtok(array, " "))
{
//later I'll just write each word into a matrix, not important right now.
while(word = strtok(NULL, " "))
{
//later I'll just write each word into a matrix, not important right now.
}
}
return 0;
}
我覺得必須有執行strtok
沒有通過該計劃中途聲明數組的一個更清潔的方式。這只是我感覺不正確。是否使用strtok
正確的方法來解決這個問題?我寧願不使用固定大小的數組,因爲我喜歡一切都是動態的,這就是爲什麼我開始懷疑使用strtok
是正確的方法。
'free(string);'爲什麼?我沒有看到任何'malloc','getstr()'動態分配內存嗎? – 2013-02-08 16:06:16
'char array [strlen(string)];'需要'char array [strlen(string)+ 1];' – 2013-02-08 16:06:58
@AlokSave'getstr()'動態地分配內存。 @PaulR我剛更新了它,謝謝。 – 2013-02-08 16:17:16