I am having problems splitting a string using pure C++
The string always looks like this
12344//1238
First int then // and then the second int.
Need help to get the two int values and ignore the //
I am having problems splitting a string using pure C++
The string always looks like this
12344//1238
First int then // and then the second int.
Need help to get the two int values and ignore the //
string org = "12344//1238";
size_t p = org.find("//");
string str2 = org.substr(0,p);
string str3 = org.substr(p+2,org.size());
cout << str2 << " "<< str3;
This should Split and convert to integers:
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline double convertToInt(std::string const& s,
bool failIfLeftoverChars = true)
{
std::istringstream i(s);
int x;
char c;
if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
throw BadConversion("convertToInt(\"" + s + "\")");
return x;
}
int main()
{
std::string pieces = "12344//1238";
unsigned pos;
pos = pieces.find("//");
std::string first = pieces.substr(0, pos);
std::string second = pieces.substr(pos + 2);
std::cout << "first: " << first << " second " << second << std::endl;
double d1 = convertToInt(first), d2 = convertToInt(second) ;
std::cout << d1 << " " << d2 << std::endl ;
}
Simplest way I can think of:
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
void main ()
{
int int1, int2;
char slash1, slash2;
//HERE IT IS:
stringstream os ("12344//1238");
os>> int1 >> slash1 >> slash2 >> int2;
//You may want to verify that slash1 and slash2 really are /'s
cout << "I just read in " << int1 << " and " << int2 << ".\n";
system ("pause");
}
Also nice because it's so easy to rewrite -- if, say, you decide to read in ints delimited by something else.
Take the integers in as a string. The string will then have the numbers and the // symbols. Next you can run a simple for loop looking for the '/' in the string. The values prior to the symbol are stored in another string. When '/' appears, the for loop will terminate. You now have the index of the first '/' symbol. Increment the index and copy the rest of the string using anothe for loop, in another string. Now you have two separate strings.