counter.txt
1 2 3
4 5 6 7 8 9void split_str(char line_str[10]) {
int i, j;
i=0;
char sub_str[10][20];
char *token;
token = strtok(line_str," ");
while (token != NULL) {
strcpy(sub_str[i], token);
i=i+1;
token=strtok(NULL," ");
}
for (j=0; j<=i; j++)
printf("The char is %s\n",sub_str[j]);
} //split_str
void main() {
file_ptr=fopen("counter.txt", "r");
while ( fgets ( line, sizeof line, file_ptr ) != NULL ) {
split_str(line);
}
开发者_JAVA百科fclose ( file_ptr );
}
Result:
The char is 1 The char is 2 The char is 3The char is 。" //a space with double quota
The char is 4 The char is 5 The char is 6The char is 。"
The char is 7 The char is 8 The char is 9 The char is 。"。is space, this web site trimmed
there are some char " "" a space with double quota that i unexpected, what is that? thanks
What you see is garbage data in sub_str
because this code is incorrect:
while (token != NULL) {
strcpy(sub_str[i], token);
i=i+1;
token=strtok(NULL," ");
}
for (j=0; j<=i; j++)
printf("%s\n",sub_str[j]);
The for
loop should run until j < i
here. This is because at sub_str[i]
you just have some dummy value, since after i=i+1
you exit the while
loop on the NULL token.
Try to simulate it "in your head" or run in a debugger to see the problem in action.
精彩评论