2016-04-13 132 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