Solved

Tokenizing strings in C

Posted on 2010-11-25
11
431 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
 
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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

760 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now