嗨,我早些时候发了一个帖子,虽然我认为它很模棱两可,所以我会再试一次,换个说法。
我正在尝试编写一个程序,该程序接受两个英文数字的输入并将它们转换为整数(使用数组),运行计算然后将它们转换回英文单词。
例如:
用户输入:sixty_six + 6 输出:seventy_two
用户输入:40_4 - 4 输出:40
ETC
然而,我一直无法在我的代码中找出问题,花了最后一个小时左右试图找到问题,尽管我无法做到。所以希望这里有人可以帮助我。
我的代码在cout
那里,所以它在循环中出错了,它似乎按预期运行,直到第二个 cout 行。意味着它输出the token is forty
andtens is euqal to
然后它失败并终止:
nt 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);
cout << "Token is: '" << token << "'" << std::endl;
for (int i = 0; i < 20; i++) {
if (token == tens[i]) {
result_ten = i * 10;
n.erase(0, pos + delimiter.length());
cout << "tens is equals to: " << result_ten << endl;
} else if (token == units[i]) {
result_unit = i;
n.erase(0, pos);
}
}
result_ten = (result_ten + result_unit);
cout << "ten is equals to: " << result_ten << endl;
}
return result_ten;
}
正在使用的数组:
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"};
提前致谢。如果有什么不清楚的地方,我会尝试更好地解释它。