Question on how to use strtok

This is a discussion on Question on how to use strtok within the C Programming forums, part of the General Programming Boards category; Hey, I am trying to read in input from the user such as a character that is followed by an ...

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    60

    Question on how to use strtok

    Hey, I am trying to read in input from the user such as a character that is followed by an integer, and depending on what that character is , perform different tasks.
    I have come up with the following code which works fine for one char - one int:
    Assume that the string that is passed to this function is: "a 53"

    Code:
    void tokenizeAstring(char string[])
    {
    	char *string1;
    	int value1;
        string1 = (char *)strtok(string," ", "\n", "\t");	/*break up the string for the first time, now only number values will remain*/
        while( string1 != NULL) {				/*while string is not empty*/
    		   value1 = atoi(string1);			/*using the function atoi to convert a string into an integer*/
               string1 = (char *)strtok(NULL," ", "\n", "\t");  /*assigns another piece to string, if this function is called propertly,*/
    															/*it will be NULL and end the loop*/
        }
    	printf("The value of val is: %d\n", value1); /*debugging check. If input was "a int", then value1 equals that int*/
    }
    The integer value1 holds the value 53 from the above sample input, and so the printf statement prints "The value of val is: 53".

    My question is, how do i go about receiving two integers from the user (for example input would be "a 53 19") and store them in two different variables, the value1 that already exists and say to value2 that I would declare etc. When I try it on a modified version of the above example I get fragmantation errors, or the values equal zero. I have no idea what to do.

  2. #2
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Ha! There is probably a bug in the forum design since if you go all to the right the letters our outside the margins (at least at the latest firefox)

    Your code seems to work fine. Here is what you can do:
    Code:
    void tokenizeAstring(char string[])
    {
        char *string1;
        int value[10], j, i=0;
        string1 = (char *)strtok(string," ", "\n", "\t");
        while( string1 != NULL) {			
    	    value[i++] = atoi(string1);			
                string1 = (char *)strtok(NULL," ", "\n", "\t");  /
        }
        for (j=0; j < 10; j++)
    	printf("The value of val is: &#37;d\n", value[j]); 
    }
    So you hold the values in an array. Then your print them. It works fine

    EDIT: Your problem was probably that you got the first two results from the while-loop. You need to get the two last results. For example if you have "a 12 13" the first iteration will store "a\0", so atoi returns 0, the second iteration will store "12\0" so atoi will make it 12 and the third 13.
    So it will print:
    The value of val is: 0
    The value of val is: 12
    The value of val is: 13
    garbage
    garbage
    garbage
    ...
    Last edited by C_ntua; 09-25-2008 at 04:03 PM.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
        string1 = (char *)strtok(string," ", "\n", "\t");
    You probably aren't including <string.h>, as the function call above has too many arguments for strtok(). If you want to split on space, newline and tab, you should have one single string with three characters in it.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  4. #4
    Registered User
    Join Date
    Sep 2008
    Posts
    60
    Thanks C_ntua , that helped me alot!
    I should've thought of using an array.

    Also matsp, you were right. I didnt include <string.h>.
    So I included it, and now I am getting these errors:

    c2.c: In function `tokenizeDstring':
    c2.c:44: too many arguments to function `strtok'
    c2.c:47: too many arguments to function `strtok'

    it works fine if I take <string.h> off my code.
    What is this about?
    Last edited by gp364481; 09-25-2008 at 06:53 PM.

  5. #5
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Dunno why it works without string.h. It is defined elsewhere also? Include it though and just do this:
    Code:
    strtok(string1, " \n\t") //note the space inside the " "
    as mastp said. Or google strtok() do use it correctly

  6. #6
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,831
    Better to have <string.h>.

    Compiler then knows enough to check the arguments for you... and complain since you put too many.

    Without it, the compiler has nothing to go on. Your code compiles without any message but the code it generated will have flaws. That's a disaster waiting to happen during runtime... and ten times harder to debug.

  7. #7
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,422
    Quote Originally Posted by C_ntua View Post
    Dunno why it works without string.h.
    Because there's an evil rule in C that allows in.
    To clarify: This is no better than not including it. It's very, very bad not to include the proper header. Always do it.

    nonoob explains this very well.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Registered User
    Join Date
    Aug 2008
    Posts
    67
    My question is, how do i go about receiving two integers from the user (for example input would be "a 53 19") and store them in two different variables, the value1 that already exists and say to value2 that I would declare etc. When I try it on a modified version of the above example I get fragmantation errors, or the values equal zero. I have no idea what to do.
    I'm at work and don't have a compiler handy, but here is an example. Keep in mind, I'm a hobbiest and am not a strong coder. This code may not even be correct. It's only to give you some ideas.

    Code:
    #include <string.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    #define CMD_SYNTAX -1
    
    int command_a(char *parameters);
    int command_b(char *parameters);
    int command_c(void);
    
    int main(void) {
    	char input[] = "a 53 19";
    	char *command = NULL;
    
    	command = strtok(input, " ");
    	if (command == NULL)
    		command = input; // no spaces in input
    
    	if (strcmp(command, "a") == 0) {
    		if (command_a(input) == CMD_SYNTAX)
    			printf("Invalid syntax for command: a\n");
    	} else if (strcmp(command, "b") == 0) {
    		if (command_b(input) == CMD_SYNTAX)
    			printf("Invalid syntax for command: b\n");
    	} else if (strcmp(command, "c") == 0) {
    		command_c();
    	} else {
    		printf("Invalid command.\n");
    	}
    	
    	return 0;
    }
    
    int command_a(const char *parameters) {
    	int min = 0;
    	int max = 0;
    	char *pstr = NULL;
    
    	pstr = strtok(parameters, " ");
    	if (pstr == NULL)
    		return CMD_SYNTAX;
    	min = atoi(pstr);
    
    	pstr = strtok(NULL, " ");
    	if (pstr == NULL)
    		return CMD_SYNTAX;
    	max = atoi(pstr);
    
    	// Do stuff with min and max
    
    	return 0;
    }
    
    
    int command_b(const char *parameters) {
    	int port = 0;
    
    	char *pstr = strtok(parameters, " ");
    	if (pstr == NULL)
    		return CMD_SYNTAX;
    	port = atoi(pstr);
    
    	// Do stuff with port
    
    	return 0;
    }
    
    int command_c(void) {
    	// Do stuff
    
    	return 0;
    }

  9. #9
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    I am surprised Elysia didn't point out her loathing of strtok(). Typically when you do stuff like this, there is bound to be a link-time error. If by some fluke this does compile into an executable, which is highly improbable, a vortex to hell will open up through your floppy drive (They open up here because floppy drives are a cheap replacement). If you don't have a floppy drive (like me) then the vortex will usually open up through your CDRW drive or DVD drive. Its tough when your program causes this kind of structural damage to your computer, but its a cold, fast lesson to learn early on in programming.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 20q game problems
    By Nexus-ZERO in forum C Programming
    Replies: 24
    Last Post: 12-17-2008, 04:48 PM
  2. a question about strtok.
    By Masterx in forum C++ Programming
    Replies: 24
    Last Post: 11-18-2008, 10:09 PM
  3. strtok question
    By neandrake in forum C++ Programming
    Replies: 1
    Last Post: 11-18-2003, 02:51 AM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 08:22 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21