Mur*_*ula -4 c++ iteration for-loop
我的印象是以下代码会打印出"hello world",但它根本不打印任何东西.为什么?使用g ++ 4.2.1和cl ++ 3.2编译.
void iterateBackwards(){
std::string hiThere = "dlrow olleh";
for ( int i = hiThere.length(); i == 0; i--) {
std::cout << hiThere[i];
}
}
Run Code Online (Sandbox Code Playgroud)
你的条件应该是i >= 0,而不是i == 0(一个for循环在条件出现时false立即退出,在你的例子中就是这种情况).
此外,一旦你解决了这个问题,你也应该修改赋值i,因为下标运算符接受从零开始的索引; 这意味着当i == hiThere.length()您访问字符串的终止符时,您可能对输出没兴趣.
这应该更好:
void iterateBackwards(){
std::string hiThere = "dlrow olleh";
for ( int i = hiThere.length() - 1; i >= 0; i--) {
std::cout << hiThere[i];
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个实例.