下面的代碼的輸出是0.我不明白爲什麼。 (我知道我已經在這段代碼中提出了關於編譯器錯誤的一個問題,現在它正在運行,但是不能正常工作。)不知道爲什麼我的str2Int函數返回0
任何人都有想法嗎?或者有更好的方式來編寫我的str2Int函數?它應該採取像「2833812」的字符串,並將其轉換爲int 2833812.
#include <iostream>
#include <map>
#include <math.h>
const char digit_ints[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
std::map<char,int> digit_map;
int str2Int(const std::string& S) {
int sz(S.size()), sum(0);
if (sz == 0) {
std::cout << "str2Int() cannot take an empty string as a parameter." << std::endl;
return -1;
} else {
int sum(0);
for (int j(0), k(sz - 1); j < sz; ++j, --k) {
if ((S[j]) < '0' || (S[j]) > '9') {
std::cout << "str2Int can only take strings with chars '0' through '9' as parameters." << std::endl;
return -1;
} else {
sum += digit_map[S[j]] * (int)pow(10.0, k);
}
}
}
return sum;
}
int main() {
for (int i = 0; i < 10; ++i)
digit_map.insert(std::pair<char,int>(digit_ints[i], i));
std::cout << str2Int("3421");
return 0;
}
這些全球'map's是極其醜陋的和多餘的,和'(INT)POW(10.0,K);'是最差計算10到整數次方的可能方法。 '#include'已棄用,您正在尋找'#include '。 –
2013-12-21 21:11:39
現在它已修復。請求代碼審查。 codereview.stackexchange.com –