#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    19
    Rep Power
    0

    Question on strtok(), text adventure game


    Hey devshed,

    Right now I'm working on a little text adventure game in which the player is given a description of their current location, and can interact with the world by typing a string such as "look around".

    I understand how to do everything after this to respond to the player using strtok(), but how would I detect if they didn't type anything after the first word?

    For example, if the player typed only "look " I would have the program respond with "look at what?"

    Thanks in advance !
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2009
    Posts
    149
    Rep Power
    37
    if you have the user input stored in a string, use strtok() to split it up into however many words the user entered. From there you only need to decide on how to handle responding to this string.

    A nice example is easily found by googling strtok():
    http://www.cplusplus.com/reference/cstring/strtok/

    Following this example, you will know the user didn't enter any more strings because strtok will return a null pointer. RTFM.
  4. #3
  5. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,392
    Rep Power
    1871
    Perhaps by having a function which returns an array/list of tokens based on a line of user input.

    If only one word was typed, then the length of that array/list would be 1.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    19
    Rep Power
    0
    Originally Posted by salem
    Perhaps by having a function which returns an array/list of tokens based on a line of user input.

    If only one word was typed, then the length of that array/list would be 1.
    I'll give this a try, thanks o:
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    19
    Rep Power
    0
    Originally Posted by jakotheshadows
    if you have the user input stored in a string, use strtok() to split it up into however many words the user entered. From there you only need to decide on how to handle responding to this string.

    A nice example is easily found by googling strtok():
    http://www.cplusplus.com/reference/cstring/strtok/

    Following this example, you will know the user didn't enter any more strings because strtok will return a null pointer. RTFM.
    This is a really good example, thanks!

IMN logo majestic logo threadwatch logo seochat tools logo