Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

A source code which give unexpect result. Please help to check !!!

j9678j9678 Member Posts: 16
#include
#include
#include
void main(){
int i=0, j=0;
char word[32], *token, *array[4][4];
FILE *infile;
if ((infile = fopen("inword.txt", "r")) != NULL)
while (fgets(word, 32, infile) != NULL){
token = strtok(word, " ");
while (token != NULL){
array[i][j++] = token;
token = strtok(NULL, " ");
}
i++;
j=0;
}
printf("%s", array[0][0]);
getchar();
}

The inword.txt file contains some "word" :
" abc def ghi
jkl mno pqr stu
vwx yz
"
If I want to print out "array[0][0]". It should be "abc". But the result is "vwx". Also, [1][0] gives "vwx". [0][1] and [1][1] give "yz". Which are all unexpected result.
Since I know this problem is because of the "refresh" of "token". The "array[][]" always link to the most update data of "token". But I just don't know how to solve this problem. Pls help !!!

Comments

  • stoberstober Member Posts: 9,765 ✭✭✭
    [blue]just in case you havn't figured it out already, you can't do it that way. see [red]RED[/red] below for one way to fix it. I didn't compile and run it, but I think that should fix it up.[/blue]

    : #include
    : #include
    : #include
    : void main(){
    : int i=0, j=0;
    : char word[32], *token, *array[4][4];
    : FILE *infile;
    : if ((infile = fopen("inword.txt", "r")) != NULL)
    : while (fgets(word, 32, infile) != NULL){
    : token = strtok(word, " ");
    : while (token != NULL){
    : array[i][j++] = [red]strdup(token)[/red];
    : token = strtok(NULL, " ");
    : }
    : i++;
    : j=0;
    : }
    : printf("%s", array[0][0]);
    : getchar();
    : }
    :
    : The inword.txt file contains some "word" :
    : " abc def ghi
    : jkl mno pqr stu
    : vwx yz
    : "
    : If I want to print out "array[0][0]". It should be "abc". But the result is "vwx". Also, [1][0] gives "vwx". [0][1] and [1][1] give "yz". Which are all unexpected result.
    : Since I know this problem is because of the "refresh" of "token". The "array[][]" always link to the most update data of "token". But I just don't know how to solve this problem. Pls help !!!
    :
    :

Sign In or Register to comment.