@Lokno 已经为您提供了正确答案。但是,让我对您的代码进行更多的挑剔,以向您展示一些其他替代方案并纠正一些小错误。
首先,您实际上并没有发布编译示例,因为您忘记显示包含的标头<iostream> 和<string>,也没有显示代码中隐含的using namespace std;。
其次,对于常规的for 循环,最好将循环变量保留在循环内,除非您确实需要将其用作返回值。还有prefer pre-increment++i 超过后增量i++。此外,由于您已确定正确的循环索引,因此没有理由在未检查的 [] 版本上使用边界检查元素访问 at()。
在 C++11 中,你有 range-for 循环,它允许更短和更简单的代码,我还使用了 auto,你可以使用 char。不幸的是,没有反向 range-for 循环。如果您使用i >= 0 而不是i > -1,正确的基于索引的反向for 循环可能更易于阅读。
然后有一个使用std::copy 的基于算法的循环,您可以使用std::string 的迭代器接口(特别是反向迭代器rbegin() 和rend())通过绑定的ostream_iterator 复制每个字符到标准输出。
顺便说一句,我使用分隔符 "|" 而不是换行符,以便更轻松地查看内容,适应您的口味。无论如何,使用std::endl 可以有performance implications,因为它每次都会刷新输出缓冲区。
#include <algorithm>
#include <iterator>
#include <iostream> // you forgot this
#include <string> // you forgot this
int main()
{
using namespace std; // you forgot this
// let's pretend this is the string
string myAnimal = "Please enter the name of your favorite animal.";
// keep the loop variable local, prefer pre-increment
for (int i = 0; i < myAnimal.length(); ++i)
cout << myAnimal[i] << "|"; // prefer [] over at()
std::cout << "\n";
// C++11 range-for
for (auto c : myAnimal)
std::cout << c << "|";
std::cout << "\n";
// index-based reverse loop
for (int i = myAnimal.length() - 1; i >= 0; --i)
cout << myAnimal[i] << "|";
std::cout << "\n";
// algorithm-based reverse loop
std::copy(myAnimal.rbegin(), myAnimal.rend(), ostream_iterator<char>(cout, "|"));
std::cout << "\n";
// main implicitly return 0
}
Live Example。 PS:main() 成功后隐式返回0。