JustSomeGuy wrote:
I have a string that looks like:
"123.45:123.45"
I have two suggestions:
This first one uses a dummy character to use istringstreams capabilities
for parsing...
(You can extend this to more floats by iterating until iss fails....)
using namespace std;
string x("123.45:123.46");
char colon; // Store the colon (or any other character)
float f1, f2; // Our target floating numbers
//Initialize an istringstream
istringstream iss(x);
// Extract the tokens
iss>>f1>>colon>>f2;
The second approach uses the strings find function to figure out the
location of the colons, then send the substring to isstream
string x("123.45:123.46:305.37");
istringstream iss("");
vector<double> mFloats;
string::size_type next_colon;
float temp = 0.0f;
x = std::string("3.0");
do
{
next_colon = x.find(':'); // Find next colon
iss.clear(); // Needed to reuse iss
iss.str(x.substr(0, next_colon)); // Use the first token
x = x.substr(next_colon+1); // Update x (You may want to use a temp
string)
iss>>temp; // Extract the current float
mFloats.push_back(temp); // Add float to the vector
}while(string::npos != next_colon);
// Output the elements
size_t doubles = mFloats.size();
cout<<"Found "<<doubles<<" number..."<<endl;
for(size_t i=0; i<doubles; i++)
{
cout<<"\t"<<i<<": "<<mFloats[i]<<endl;
}