leopragi
leopragi

Reputation: 471

strtok function does not function properly

LOG.txt file :

2327 - Your account is created on 01/09/15 # 
2327 - Amount:100 withfrawed from your account on 01/09/15 #

This code show me a output at first time compilation and other other output at second time compilation. What is the mistake i have make

#‎include‬<stdio.h>
#include<conio.h>
#include<string.h>
FILE *fp;

void main()
{
    int i=0;   
    char temp[10],log[10000],*token;
    char s1[2] = "#",s2[2] = "-",logger[100][70],no[100][10];
    clrscr();

    fp=fopen("LOG.TXT","r");

    while(fscanf(fp,"%s",temp)!=EOF)
    {
        strcat(log,temp);
        strcat(log," ");
    } 
    fclose(fp);
    printf("%s",log);
    token = strtok(log,s1);

    while(token!=NULL)
    {
        strcpy(logger[i],token);
        i++;
        token = strtok(NULL,s1);
    }

    i=0;
    token = strtok(logger[i],s2);
    while(token!=NULL)
    {
        strcpy(no[i],token);
        i++;
        token = strtok(logger[i],s2);
    }
    getch();
}

Upvotes: 1

Views: 151

Answers (2)

Gopi
Gopi

Reputation: 19864

char log[10000];

Here log is uninitialized so strcat() will search for NULL terminator and log will not have it because it is unintialized so you need to initialize log before doing strcat()

Using uninitialized variables lead to undefined behavior so strtok() not working might be because of this.

You can do

char log[10000] = {0};

or

memset(log,0,sizeof(log));

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

Your problem is most likely here:

strcat(log,temp);
strcat(log," ");

You do not initialize log which means the contents is indeterminate and using log this way leads to undefined behavior.

Remember that strcat looks for the string terminator character '\0' to know where it should start appending, and uninitialized local non-static variables will have seemingly random contents.

Upvotes: 2

Related Questions