C++使用for循环反向打印字符串

Bob*_*bby 1 c++ string reverse for-loop

我有一个程序,使用for循环打印出字符串的字符.它还必须反向打印相同的字符,这是我遇到问题的地方.有人可以帮我弄清楚为什么第二个for循环没有执行?

int main()
{
    string myAnimal;

    cout << "Please enter the name of your favorite animal.\n";
    cin >> myAnimal;

    // This loop works fine
    int i;
    for(i = 0; i < myAnimal.length(); i++){
        cout << myAnimal.at(i) << endl;
    }

    // This one isn't executing
    for(i = myAnimal.length(); i > -1; i--){
        cout << myAnimal.at(i) << endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Lok*_*kno 5

您需要首先将i分配给长度减去1或数组中的最后一个索引值.

for(i = myAnimal.length()-1; i >= 0; i--){
    cout << myAnimal.at(i) << endl;
}
Run Code Online (Sandbox Code Playgroud)

  • 附录:这就是运行时错误消息"在抛出'std :: out_of_range''或类似的实例之后调用的终止,你本来应该告诉你的. (2认同)