How to Convert e.x. 2/3 or 1/2 in input to float in cpp
string s="2/3";
float x=stod(s);
CodePudding user response:
You could try something like:
int a,b;
string s="2/3";
sscanf(s.c_str(), "%d/%d", &a, &b);
float x = float(a)/b;
Of course, you have to do some validations around b
being zero.
CodePudding user response:
You can use std::string::find()
to find the /
char, and then use std::string::substr()
to split the string into its numerator and denominator portions.
Then use std::stod()
to convert each to a number:
std::string numerator = s;
std::string denominator = "1";
auto pos = s.find("/");
if (pos != std::string::npos)
{
numerator = s.substr(0, pos);
denominator = s.substr(pos 1);
}
double n, d;
double result = 0;
try
{
n = std::stod(numerator);
d = std::stod(denominator);
if (d != 0)
{
result = n / d;
}
}
catch(std::exception& ex)
{
// parse error
}