i am reading from file called inputfile and storeing in char array line. Lets say the word in char array line is "black cat". than I am strtok word "black" and puting in ch. After that iam testing if the 1st word is black or not. Inside the if statment iam getting the 2nd word by using sttok, so tptr will have "cat". than iam using strcpy and strcat so than char array called name will have "black cat and dog".

Problem: problem iam haveing on line

tptr = strtok(NULL," ");

To me it look fine and i am not sure what iam doing wrong. any troughs?

while(fscanf(inputfile, "%s", line)) != EOF)
{
   if(tptr != NULL)
   {
     strcpy(ch, tptr);
  
      if(strcmp(ch, "black") == 0)
      {
        tptr = strtok(NULL," ");
        strcpy(name, tptr);
        strcat(name," and dog");
      }
   }
}

Fist of all, fscanf() will not give you "black cat" because it will stop reading the file when it encounters the first space, so all it will give you on the first iteration of that loop is "black". Your use of strtok() in this instance is unnecessary because the line will have no spaces.

If you want the entire line, including spaces, you have to call fgets() instead of fscanf(), e.g.

char line[90];
while( fgets(line, sizeof(line), inputfile) != NULL) 
{
    char *tptr = strtok(line, " "); // get first token
    while( tptr != NULL)
    {
       if( strcmp(tptr,"black") == 0)
       {
           // do something with it
       }
       tptr = strtok(NULL," ");  // get another token 
    }
}

Edited 4 Years Ago by Ancient Dragon: n/a

thanks it seem to be working now. only thing is for some reason its printing
"black cat\nand dog" its puting enter between in middle of the array. may be am mistaking how strcpy and strcat works.

tptr = strtok(NULL," ");
        strcpy(name, tptr);
        strcat(name," and dog");

fgets() puts the '\n' at the end of the string because it is in the file. You need to erase it

while( fgets( ... ) )
{
   line[strlen(line)-1] = '\0';  // erase the '\n'
}

fgets() puts the '\n' at the end of the string because it is in the file. You need to erase it

while( fgets( ... ) )
{
   line[strlen(line)-1] = '\0';  // erase the '\n'
}

dude thanks alot. it works now :)

This article has been dead for over six months. Start a new discussion instead.