Debugging my current code, more efficient ways to do it
I'm currently writing a program that allows the user to input words such
as "four" + "fifty" of "six" + "fifty_five". The program with then use an
array to find the corresponding number, do calculations with the ints and
then change the ints back to word form. However I'm not currently getting
any output at all which leaves me to believe one of my loops aren't
running correctly or my calculations are off. I'll just place the part of
the code which I believe to be the problem, as I'm sure errors will be
found in that.
Function to convert int to string and return the result.
// Converts the calculated int to a string and then returns the result.
string Wordnum::write_number(int n) {
int ten;
if (n > 10) {
ten = n / 10;
n = n % 10;
}
string result = tens[ten] + "_" + units[n];
return result;
}
Function to change string to int to do calculations:
int Wordnum::read_number(string n) {
int result_ten = 0;
int result_unit = 0;
int j = 0;
// Loops through input and turns it all to lower case.
while (n[j]) {
char c;
c = n[j];
c = (tolower(c));
n[j] = c;
j++;
}
string delimiter = "_";
size_t pos = 0;
string token;
// Checks for the _ delimiter and takes the first token then checks it
against the array to "convert" from string to int.
while ((pos = n.find(delimiter)) != string::npos) {
token = n.substr(0, pos);
for (int i = 0; i < 20; i++) {
if (token == tens[i]) {
result_ten = i * 10;
}
if (token == units[i]) {
result_unit = i;
}
}
n.erase(0, pos);
}
result_ten = (result_ten + result_unit);
return result_ten;
}
How the arrays are initialized.
string const Wordnum::units[] = {"zero", "one", "two", "three", "four",
"five",
"six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
string const Wordnum::tens[] = {"zero", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"};
All other functions are just overloaded operators, which were working in
the past. So I'm confident te problem is in here somewhere. All help will
be greatly appreciated, thanks in advance. ^^
Examples of how it should work is:
input: fifty_five + five output: sixty
input: ten - four output: six
At the moment, since I changed it to use a delimiter, I have been getting
no output what so ever, the code just fails.
No comments:
Post a Comment