Tokenizing strings in C

Hello,
I have problem with  strtok() to parse user's one line command correctly. The user will enter a command, for instance, display testfile.txt and the file should be displayed. However, in my case, if I enter display testfile.txt  the error message "Invalid entry, program exiting...." is displayed and the program exits. If I enter just display the error message, "File does not exist or error in display" and program exits. If I enter exit, the thank you message is displayed, and the program exits. Looks like strtok() is only processing the first command but not the second (name of the file). How can I make the strtok() functioning properly? Your advice is appreciated.
#include <stdio.h> 
#include <stdlib.h>
#include <string.h>


int main ()
{
 

 FILE *fp; 
 char line[100];
 char command[30];
 char *userfile;
 char *choice;

  printf("Please enter a command : ");
  gets(command);
    choice=strtok(command, "");
    userfile=strtok(NULL, "");
     if (strcmp(choice,"display") ==0)
     {
      fp = fopen(userfile, "r"); 
      if (fp==NULL){
      printf("File does not exist or error in display\n");
      exit(1);
      }
      /*read and display the file*/
      while (fgets(line, 127, fp) != NULL)
      printf("%s", line);
      fclose(fp); /*close the file*/
     }
     else if(strcmp(choice,"upper") ==0 )/*convert to uppercase*/
     {
	/*code */
     }
     else if(strcmp(choice,"lower") ==0)/*convertto lowercase*/
     {
         /*code */
     }
     else if(strcmp(choice,"exit") == 0)
     {
     printf("Thank you!\n"); /*print thank you and exit*/
     }
     else
     {
     printf("Invalid entry, program exiting....\n"); /*print error message and exit*/
     return 0;
     }
  } /*end of main*/

Open in new window

Mathilda100Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Xper4netConnect With a Mentor Commented:
Strange, there's no separator declared in your calls :

choice=strtok(command, "");
userfile=strtok(NULL, "");


Then strtok can't do anything... I suppose that it would be a space:

    choice=strtok(command, " ");
    userfile=strtok(NULL, " ");
0
 
masheikCommented:
why dont you use command line arguments instead of strtok?

int main(int argc,char *argv[])
{
  }

Example can be found here
http://www.cprogramming.com/tutorial/c/lesson14.html
http://www.eskimo.com/~scs/cclass/notes/sx13.html
0
 
masheikConnect With a Mentor Commented:
choice=strtok(command," ");
    userfile=strtok(NULL," ");
delimiter is space
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
masheikCommented:
>>>Xper4net:
oh ..I did not refresh the page..
0
 
Mathilda100Author Commented:
Sorry for typing error: I do have the space " " as delimiter in my code but the way I am using strtok()  does not work.
0
 
masheikCommented:
Here is a example code ,

#include <stdio.h>
#include <string.h>

int main()
{
  char str[] = "Test1,Test2,Test3,Test4,Test5";
  const char *delimiter = ",";
  char *tok = NULL;
  tok = strtok(str,delimiter);
  printf("token = %s \n",tok);
  while (tok != NULL)
  {   
     tok = strtok(NULL,delimiter);
	 printf("token = %s \n",tok);
  }
  return (getchar());
}

Open in new window


The strtok() function returns a pointer to the next "token" in str, where delimiter contains the delimiters that determine the token. strtok() returns NULL if no token is found
0
 
Xper4netCommented:
Try the following :

    choice=strtok(command, " ");
     if (strcmp(choice,"display") ==0)
     {
         userfile=strtok(NULL, " ");
0
 
Infinity08Commented:
>> if I enter display testfile.txt  the error message "Invalid entry, program exiting...."

The easiest way to fix this, is to either print out the 'choice' variable (after the strtok calls), or look at it with a debugger, to see what it actually contains.

That will give you an indication of what's going wrong.
0
 
masheikCommented:
Your code works fine for me...
#include <stdio.h>
#include <string.h>
void tusermain (void);
int main()
{
    tusermain();
    return (getchar());
}

void tusermain (void)
{
    FILE *fp;
    char line[100];
    char command[30];
    char *userfile;
    char *choice;

    printf("Please enter a command : ");
    gets(command);
    choice=strtok(command," ");
    userfile=strtok(NULL," ");
    printf(" choice     = %s \n",choice);
    printf(" usef file  = %s \n",userfile);
    if (strcmp(choice,"display") ==0)
    {
        fp = fopen(userfile, "r");
        if (fp==NULL)
        {
            printf("File does not exist or error in display\n");
            
            exit(1);
        }
        /*read and display the file*/
        while (fgets(line, 127, fp) != NULL)
            printf("%s", line);
        fclose(fp); /*close the file*/
    }
    else if(strcmp(choice,"upper") ==0 )/*convert to uppercase*/
    {
        /*code */
    }
    else if(strcmp(choice,"lower") ==0)/*convertto lowercase*/
    {
        /*code */
    }
    else if(strcmp(choice,"exit") == 0)
    {
        printf("Thank you!\n"); /*print thank you and exit*/
    }
    else
    {
        printf("Invalid entry, program exiting....\n"); /*print error message and exit*/
        return 0;
    }
    getchar();
} 

/*console o/p *
--------------
Please enter a command : display Test.txt
 choice     = display
 usef file  = Test.txt
Test File
Test1
Test2;
*/

Open in new window

0
 
masheikCommented:
You can use the command line to give inputs.

compile and run the example  code..given below,

Go to the directory where user EXE exists and

in windows ,
Strart->Run->cmd-> cd your directory where exe exists

and

>>>YourExename.exe display Test.txt
#include <stdio.h>
#include <string.h>
void tusermain (int argc,char *argv[]);
int main(int argc,char *argv[])
{
    tusermain(argc,argv);
    return (getchar());
}

void tusermain (int argc,char *argv[])
{
    FILE *fp;
    char line[100];
    char command[30];
    if(argc != 3)
    {
        printf("Invalid number of arguments\n");
        exit(1);
    }
    if (strcmp(argv[1],"display") ==0)
    {
        fp = fopen(argv[2], "r");
        if (fp==NULL)
        {
            printf("File does not exist or error in display\n");
            getchar();
            exit(1);
        }
        /*read and display the file*/
        while (fgets(line, 127, fp) != NULL)
            printf("%s", line);
        fclose(fp); /*close the file*/
    }
    else if(strcmp(argv[1],"upper") ==0 )/*convert to uppercase*/
    {
        /*code */
    }
    else if(strcmp(argv[1],"lower") ==0)/*convertto lowercase*/
    {
        /*code */
    }
    else if(strcmp(argv[1],"exit") == 0)
    {
        printf("Thank you!\n"); /*print thank you and exit*/
    }
    else
    {
        printf("Invalid entry, program exiting....\n"); /*print error message and exit*/
        return 0;
    }
    getchar();
} /*end of main*/

Open in new window

Console O/P:
----------------
E:\ExampleEE\Debug>EE_Examples.exe display Test.txt
Test File
Test1
Test2;
FileContents displayed

0
 
Mathilda100Author Commented:
I checked my code and yes: I had actually  used "" as delimiter instead of " ". Thank you for your help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.