-2

I am trying to learn c++, and for an assignment I have ran into a problem. I am trying to get an integer value from a string that a user enters all on one line.

Ex.) The user inputs: "Change value to 15."

What is the best way of getting the 15 from that string? I have looked around for a while, but could only find if a string was only integers.

Thanks in advance!

furuf
  • 39
  • 1
  • 6

2 Answers2

2

Why not use a mixture of getline(grabs your whole line) and string stream(tokenizes the input) and put them all in a vector(easier to use than an array), grab the one at .size()-1 and do an atoi on that. Might be overkill, but string stream could do what you want. For a small tut this could help http://www.dreamincode.net/forums/topic/95826-stringstream-tutorial/

snurby77
  • 310
  • 3
  • 13
0

This might not be the best way but to get something done now you can use strtok to tokenize your input string and then examine the tokens for your integer value integer. One of the answers here [link] suggests using strtok to tokenize a string.

If you know the format of you string or know that there will always be a single integer value then you can use string::find_first_of and string::find_last_of [link] and then just get the substring and use string::stoi.

Community
  • 1
  • 1
deathly809
  • 384
  • 4
  • 11
  • 1
    Mentioning `strtok()` is probably the worst advice you can give. – πάντα ῥεῖ Jul 24 '14 at 15:10
  • @πάνταῥεῖ I didn't say to use it in production code. I said for now so he can work on his code and then when he finds his fix come back and make changes. Also I offered alternative solutions if he knows the format of his input. – deathly809 Jul 24 '14 at 15:18
  • 1
    _"I didn't say to use it in production code."_ Nope, that doesn't make it better, you shouldn't have mentioned this at all. That's not useful! (also [have a look here](http://stackoverflow.com/a/10526343/1413395) or at the numerous other Q&A, that mention and explain, why this is discouraged). – πάντα ῥεῖ Jul 24 '14 at 23:41