我基本上想從stdin中取一行輸入,抓住'strings'(一個由空格分隔的char數組),然後將每個'string'放入數組中的char []。我已經嘗試過使用fgets,getline和strtok;我不想使用外部庫或任何Unix不可用的東西。我在這裏看到很多類似的問題,所以我很抱歉如果這個問題已經得到解答,但是我找不到一個簡單明瞭的方法來做到這一點。C Unix - 解析一行字符
謝謝,我很抱歉,如果我錯誤地稱爲什麼,我非常不習慣C.
編輯:好了,這裏就是我試過最近:
#include <string.h>
#include <stdio.h>
int main() {
const char str[80] = "This is a | test";
const char s[2] = " ";
char *token;
char arguments[10][50];
int i = 0;
/* get the first token */
token = strtok(str, s);
/* walk through other tokens */
while(token != NULL)
{
printf(" %s\n", token);
arguments[i] = token;
i++;
token = strtok(NULL, s);
}
return(0);
}
編輯:謝謝保羅,對同一個問題的人,因爲我有,我得到了它通過改變這行的工作:
arguments[i] = token;
到:
strcpy(arguments[i], token);
顯示你的嘗試以及失敗的方式。 'fgets()'和'strtok()'或手動解析的組合是正常的方法,所以如果這不適合你,那麼讓它適合你是你應該做的,而不是尋找另一個辦法。 – 2014-09-27 18:27:51
'arguments [i] = token;' - 你不能像這樣分配數組,你需要使用'strcpy()'。 'strtok()'修改你傳遞給它的字符串,所以你不應該使它成爲'const'。這是非常基本的,我想你需要多花一點時間學習C,然後在Stack Overflow上提出問題。 – 2014-09-27 18:44:23
我認爲'argv'(在'int main(int argc,char * * argv);')可能正是你所需要的。請注意,設計程序以獲取參數作爲命令行參數比交互式查詢用戶通常更好。不幸的是,後者是大多數書籍和課程教給你的。 – 5gon12eder 2014-09-27 18:52:02