-1
我想從文件中讀取連續的行,並通過指向字符串數組的指針指向它們。但只有第一行按預期得到輸出,之後輸出不會按需顯示。沒有從文件中獲取令牌?
input.txt:
Hi i am Michel
hello swing
how are you
O/P是:
LINE[1]=Hi i am Michel
st_arr[0]=Hi
st_arr[1]=i
st_arr[2]=am
st_arr[3]=Michel
LINE[2]=hello swing
st_arr[0]=Hi
LINE[3]=how are you
st_arr[0]=Hi
這裏是我的代碼:
main()
{
int i = 0,j=0,k=0,p=0;
char lines[10][ 50];
char words[10];
char *st_arr[20];
FILE *fp = fopen("input.txt", "r");
while (fgets(lines[i], sizeof(lines[i]), fp))
{
lines[i][strlen(lines[i])-1] = '\0';
i = i + 1;
}
fclose(fp);
printf("The value of i=%d\n",i);
for(j=0;j<i;j++)
{
printf("LINE[%d]=%s\n",j+1,lines[j]);
{
char *token=strtok(lines," ");
while(token!=NULL)
{
st_arr[p]=malloc(strlen(token)+1);
strcpy(st_arr[p],token);
printf("\tst_arr[%d]=%s\n",p,token);
token=strtok(NULL," ");
p++;
}
}
bzero(st_arr[j],sizeof(st_arr));
p=0;
}
}
是否有我顯然缺少出頭的任何問題?
此代碼看起來像一個合適的IOCCC條目。 – 2013-02-08 19:28:23
像你這樣的接縫需要熟悉一個調試器。如果你在一個基於Linux的系統上,我會推薦GDB ... – 2013-02-08 19:32:56
'input.txt'的大小是多少?你能包含內容嗎? – SparKot 2013-02-08 19:40:18