Jump to content
  • Advertisement


This topic is now archived and is closed to further replies.

Just Another Penguin

string parsing

This topic is 5965 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Okay, in a game I''m making, the player inputs a command like "move n,10" which is move north 10. How would I parse it in C++? I tried using counters and string arrays, checking for a letter, if it''s there check for the next letter and so on. I know it''s clunky, but could someone enlighten me on a better way?

Share this post

Link to post
Share on other sites
How many commands do you got? If you have a very limited num. of commands consider making them simple cases

Case 1 = Move n,1 ;
Case 2 = Move n,2 ;

where you check case n aginst your input string.

Other than that you have to write a simple parser.
In theory first you have to define a grammar. In reallife you have to "separate" the diffrent elements of your grammar/instring then parse them.

Like this:
A = "Move"
B = "n"
C = "1";

to split up the instring use spaces, commas etc to detect a new syntactic particle.

Then, let''s say you defined a simple grammar like this
EXP = A->B->C

This could mean that:
A always be a "Command Type"
B is always one of four directions (n,s,w,e)
C is always an integer.

that gives you a simple grammar like this:

Valid Exp:
CMD -> Direction -> Integer

in reality:

if CMD then Direction
if Direction then integer
return IsValidExp

INTEGER {1..100}

Parsers are not that complex as they may seem. What makes them kinda hard to get is getting used to the notation used when defining a grammar. Also the most common parser is called a "recursive descent" parser...which parses a string in a recursive manner. And as you may know recursive algorithms can be a real b*tch...

Parsers are a big thing in cs...the www is flooded with stuff about how to write and design em''.

Share this post

Link to post
Share on other sites
I don''t use them, but I remember there are some commands that only read in one word, and stop at a space. You could use those (fin, or something like that?) and the strcmp function to check commands also.

Just figured I''d present another option. Hopefully I''m not too inaccurate.

-Arek the Absolute

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!