Jump to content
  • Advertisement
Sign in to follow this  
Breander

Extracting info from a string in C++

This topic is 4013 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

I'm doing a project for school where the user will type in something like so. draw "x" at 1, 5 Now I'm reading that into a string like so string command; cin >> command; Now I need to be able to 1. get "draw" to let me know what the program is to do 2. get the character inside the quotes and transfer it into a char variable 3. and read the 2 numbers into integers x and y variables. I don't know how I am to transfer the certain parts of the string into the variables. Any help with this will be much appreciated.

Share this post


Link to post
Share on other sites
Advertisement
Well since its a project for school I won't give you the answer, but you could take a look at std::stringstream. Another option is to just parse the string yourself, think about what seperates each value in the string...

Share this post


Link to post
Share on other sites
Keep in mind that cin will read up until it hits whitespace. What I mean here is that if you say:
cin >> command

And the user types "draw x at whatever"
command = "draw", and the rest of that stuff (x at whatever) is going to stick around until the next call of cin.

You may want to look into getline to read an entire line of input.

Also, look into substr to break up the string.

Cheers,
--Brian

Share this post


Link to post
Share on other sites
Hey guys thanks for the help!
I have almost got it working by doing this


cin >> cmd;
if (cmd == "draw")
{
cin >> ws;
junk = cin.get();
symbol = cin.get();
junk = cin.get();
cin >> crap;
cin >> x1;
cin.ignore(256, ',');
cin >> y;
}



now if I type in
draw "x" at 3 , 5

it works

but if I type
draw "x" at 3, 4

it tries to read 3, into the int and goes nuts
Now I know my teacher is probably going to test both cases and probably more. is there any way to get it to ignore the comma?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

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

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!