2013-12-21 134 views
0

下面的代碼的輸出是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; 
} 
+0

這些全球'map's是極其醜陋的和多餘的,和'(INT)POW(10.0,K);'是最差計算10到整數次方的可能方法。 '#include '已棄用,您正在尋找'#include '。 – 2013-12-21 21:11:39

+0

現在它已修復。請求代碼審查。 codereview.stackexchange.com –

回答

1

還是有寫我str2Int功能的更好的辦法?

int str2Int(std::string const& str) { 
    istringstream is(str); 
    int ret; 
    is >> ret; 
    return ret; 
} 
+0

對於這個問題,只需[std :: stoi](http://en.cppreference.com/w/cpp/string/basic_string/stol) – SoapBox

+0

@SoapBox:+ infinity。 –

+0

@JohannGerell不是如果它是一個練習(你知道,在學校學習編程的人有時會做家庭作業)。 – 2013-12-21 21:20:25

4

刪除此行

int sum(0); 

從其他塊,要創建其可以被限制在其他塊,其是一種新的和可變的「隱藏」從外範圍的總和可變。您正在從外部範圍返回總和變量。

+0

關於爲什麼的任何解釋? – 2013-12-21 21:13:58

+0

除了可能的改進(在OP代碼中) - 正確的答案! –

+0

@DieterLücking無論如何,這是正確的答案之一。 – 2013-12-21 21:18:24

3

幸得克里斯·泰勒,但我只是想解釋爲什麼int sum(0);是錯誤的else分支:您聲明另一sum變量在內部塊,使陰影(隱藏)您稍後返回一個。

一種更好的方式來寫你的函數將是(沒有錯誤檢查):

int str2int(const std::string &s) 
{ 
    // do error checking, then: 
    int i = 0; 
    std::string::const_iterator it = s.begin(); 
    while (it != s.end()) { 
     i *= 10; 
     i += *it++ - '0'; 
    } 

    return i; 
} 

這是爲什麼比你現在的方法更好?

  • 它避免了全局變量;
  • 它不依賴於pow()提供了一個確切的結果(它沒有)。一般來說,當使用整數時,你不應該使用在浮點數上操作的函數。
+0

你不應該'i + = * it ++ - '0';''i * = 10之前''? – smac89

+0

@ Smac89沒錯,我不應該。 – 2013-12-21 21:24:57

+0

好的,但原因並不明顯,這就是爲什麼我問 – smac89

3

或者有更好的方式來寫我的str2Int函數?

如果您使用C++ 11:

#include <string> 

int str2Int(const std::string& str) 
{ 
    return std::stoi(str); 
} 
相關問題