Thread: Using strtok/dividing up strings

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    1

    Smile Using strtok/dividing up strings

    Hey... I'm very much a newbie to C and was hoping someone might be able to offer some help or just point me in the right direction, thanks. ^_^.

    Anyway, my program is supposed to read in a line from stdin and then break the line into words. It does this okay, but I don't know how I could modify it so that it will only continue assigning values to the variables *if* there are values to assign.

    Like, the current code (where 'search' is a space and 'end' is a newline character) is:

    first = strtok(s, search);
    second = strtok(NULL,search);
    third = strtok(NULL, search);
    fourth = strtok(NULL,end);

    This is fine if the input is four words as expected, but what I was wondering if someone could suggest some way to kind of check, like, if there are more words in the string. I'm more used to working in Java so I must admit my understanding of strtok is not very strong in C; there may be some much better way of approaching the problem.

    Anyway, I guess it's a very simple question so hopefully it can be cleared up easily, thanks.

    -Leto ^_^.

  2. #2
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    Just remove the newline character at the end of your string. The strtok function will return a NULL pointer when reaching the end of the string:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main ()
    {
       char buf[BUFSIZ];
       char *ptr = NULL;
    
       if(fgets(buf, BUFSIZ, stdin) == NULL)
          return -1;
    
       /* remove newline character */
       if((ptr = strchr(buf, '\n')) != NULL) *ptr = '\0';
    
       if((ptr = strtok(buf, " ")) != NULL)
       {
          printf("[%s]\n", ptr);
          while((ptr = strtok(NULL, " ")) != NULL)
             printf("[%s]\n", ptr);
       }
       return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strings Program
    By limergal in forum C++ Programming
    Replies: 4
    Last Post: 12-02-2006, 03:24 PM
  2. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 08:07 PM
  3. Reading strings input by the user...
    By Cmuppet in forum C Programming
    Replies: 13
    Last Post: 07-21-2004, 06:37 AM
  4. damn strings
    By jmzl666 in forum C Programming
    Replies: 10
    Last Post: 06-24-2002, 02:09 AM
  5. menus and strings
    By garycastillo in forum C Programming
    Replies: 3
    Last Post: 04-29-2002, 11:23 AM