I'm writing a program to convert from Decimal to Octal, vice versa, Hex to Decimal, vice versa, etc. Anyway so I was happily coding along when I realised that if a user entered a fraction; I would be doomed! :O
So I googled how to split a string; so that I could then divide the first number by the second.
I found a function; and I rewrote it for my own purposes. I tried it out; and the program told me the answer was infinity. I am fairly sure 25/5 != infinity: http://i31.tinypic.com/vzess5.png
Could you tell me what I have done wrong here? I'm not sure what; perhaps I could add cout everytime I do a step in the function... I'll do that and post the results.
// The string to convert
double cvtFracToNum(string num) {
string sub1, sub2; // The substrings, 1 will be divided by two to convert into a decimal.
double val = 0; // The value to return; this will be equal to sub1 / sub2.
size_t pos = num.find("/"); // Split the string around the division symbol.
if (pos != string::npos) {
size_t end = 0;
if (!(num.empty())) {
while (end != pos) {
sub1 += num[end++]; // The first substring = the first number
}
while (end != num.length()) {
sub2 += num[end++]; // The second substring = the second number.
}
} else {
sub1 = num;
sub2 = "";
}
}
double Dsub1 = atof(sub1.c_str());
double Dsub2 = atof(sub2.c_str());
val = (Dsub1 / Dsub2);
return val;
}
void DecToOct() {
string dec;
double decNum = 0;//, octNum;
cout << "What is your decimal number: ";
cin >> dec;
cin.ignore();
if (dec.find("/") != string::npos) {
string num = dec;
cout << dec << endl;
decNum = (cvtFracToNum(num)); // Handle fractions
}
cout << decNum << endl;
}
At this point it just tells me that Dsub1 / Dsub2 is infinity... I haven't even gotten to the point of converting infinity to octal yet :l
After calling std::string num.find(), use the value, the position of the '/' to to use in the std::string num.substr(start, length) function. I think what is happening is something is going wrong when you try and parse the string, and your are not passing a valid value to atof(). If you pass chars other than '0'-'9' and/or '.' the function just returns '0' hence 25/0=inf.