2016-04-13 31 views
0

我真的很困惑這個簡單的問題。 這裏是我的代碼:string.length()導致問題

#include <iostream> 
#include <string> 

int main() 
{ 
    std::string str = "bb"; 
    int counter; 
    for (counter = str.length() - 1; counter >= str.length() - 2; counter--) 
    { 
     std::cout << "counter: " << counter << std::endl; 
    } 
} 

基本上,它應該只打印兩行,然後終止該程序,但它使印刷生產線。事實上,循環不會在counter = -1停止,這很奇怪!爲什麼會發生?

+5

在C++的全局命名空間中使用'void main()'是非法的。你應該使用'int main(void)'來代替。 – MikeCAT

+5

或'int main()'。 – TartanLlama

+0

@MikeCAT:你的意思是非法?!它工作正常。 – Diamond

回答

8

std::string.length()是無符號的,所以countercounter >= str.length() - 2被轉換爲無符號值並且公式將不爲真。

嘗試使用counter + 2 >= 0 && counter + 2 >= str.length()代替。

+1

@RSahu它不會直接解決這個問題。將'str.length()'強制轉換爲正確的簽名類型也是很好的選擇。 – MikeCAT

+0

你能解釋一下嗎? str.length() - 2將等於零,否?那麼爲什麼公式會出錯? – Diamond

+0

無無符號的整數是小於0. – MikeCAT