We went into greater detail about strings in class the other day, and it brought up a potential problem. I understand that the <string> class does not provide support for converting char and int (and I assume double as well) variables to strings when the string variable is declared, although char variables can be assigned to a string variable after it is declared. I was wondering if there is a library that includes a function(s) that would allow a number to be pulled out of a string, converted to an int (or double) so it can be manipulated in some way, then converted back into a string again.
This isn't something that I need for class. I was just curious about it and my instructor wasn't aware of any existing functionality that could do this. He said I may need to write the code for it myself if I ever needed to do it.
I'll be curious from other replies, but could strtok be used here?
If this is say, an English sentence, and you can separate the pieces by using the space as a delimiter, you can then convert the element that is a number to a number, manipulate, and put the sentence back together.
Ahh yes, stringstream. Something I should be more familiar with, since I should be avoiding the old C calls. Here is a brief post that includes some howto:
Is there any function in stringstream that would support the conversion of numbers separated from a string into int or double variables and back again? I looked through what is available in that class and nothing stands out to me as having that capability.
@JMJAtlanta strtok is new to me. I think it could be helpful in this instance, since the individual tokens could be examined to see if they were a number or not. However, it still leaves me with the problem of converting the token containing a number to an int or double so it can be manipulated, then converted back into a token and reinserted into the string.
If you are examining/modifying individual tokens from the same strnig, stringstream is the tool to use, unless you're dealing with something too complicated
@Cubbi
So stringstream handles the type conversion implicitly through overloading the insertion and extraction operators?
Thanks for the great examples and demos. I was not aware of the ideone site. That is definitely going on my browser favorites toolbar.
@JMJAtlanta
I was aware of some of the cstdlib functions for converting types. What I didn't know was if they could handle numbers with more than one digit. Do they know that, for example, string a = "123"; should be equal to int b = 123; after the value is converted to an int?