Originally Posted by
laserlight
I suggest to start by removing the "Answer: " substring. A fairly direct way to do this is to observe that "Answer: " has a length of 8, so you take the substring starting from index 8 (remember to use named constants rather than magic numbers, or otherwise compute the length of "Answer: ").
With this substring, e.g., "132/643", you have a few ways by which you can extract 132 and 643. One approach is to turn it into a stringstream, and then use formatted input to read into an int, then a char, then an int.
Another approach is to use the find member function of std::string to find the '/', then get two substrings "132" and "643", and then convert them to int, e.g., by using a stringstream as in your current code.
Thanks for the inspiration. This is what I put together after finding a nice split function on the internet:
Code:
#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
#include <stdio.h>
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
int main(int argc, char* argv[])
{
std::string str(" Answer : 1/128");
std::string lookup("Answer");
if ( str.find(lookup) != std::string::npos ) {
unsigned numpos = str.find("Answer");
std::string numstr = str.substr( numpos + 9 );
std::vector<std::string> x = split(numstr, '/');
// for ( std::vector<std::string>::iterator it1 = x.begin(); it1 != x.end(); ++it1 ) std::cout << *it1 << " ; ";
std::cout << std::endl;
std::cout << (double) atoi( x[0].c_str() ) / atoi( x[1].c_str() ) << std::endl;
}
return 0;
}