Solved

Tokenizing strings in C

Posted on 2010-11-25
11
434 Views
Last Modified: 2012-05-10
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

0
Comment
Question by:Mathilda100
  • 6
  • 2
  • 2
  • +1
11 Comments
 
LVL 9

Expert Comment

by:masheik
ID: 34211767
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
 
LVL 5

Accepted Solution

by:
Xper4net earned 250 total points
ID: 34211768
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
 
LVL 9

Assisted Solution

by:masheik
masheik earned 250 total points
ID: 34211787
choice=strtok(command," ");
    userfile=strtok(NULL," ");
delimiter is space
0
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 9

Expert Comment

by:masheik
ID: 34211804
>>>Xper4net:
oh ..I did not refresh the page..
0
 

Author Comment

by:Mathilda100
ID: 34211855
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
 
LVL 9

Expert Comment

by:masheik
ID: 34211866
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
 
LVL 5

Expert Comment

by:Xper4net
ID: 34211874
Try the following :

    choice=strtok(command, " ");
     if (strcmp(choice,"display") ==0)
     {
         userfile=strtok(NULL, " ");
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 34211919
>> 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
 
LVL 9

Expert Comment

by:masheik
ID: 34211961
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
 
LVL 9

Expert Comment

by:masheik
ID: 34212605
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
 

Author Closing Comment

by:Mathilda100
ID: 34228417
I checked my code and yes: I had actually  used "" as delimiter instead of " ". Thank you for your help.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho‚Ķ
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question