C ++使用for循环反向打印字符串 [英] C++ Printing a string in reverse using a for loop
本文介绍了C ++使用for循环反向打印字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用for循环打印出字符串字符的程序.它还必须反向打印相同的字符,这就是我遇到的问题.有人可以帮我弄清楚为什么第二个for循环未执行的原因吗?
I have a program that prints out the characters of a string using a for-loop. It must also print the same characters in reverse, which is where I'm having problems. Can someone help me figure out why the second for-loop isn't executing?
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;
}
推荐答案
您需要首先将i赋给长度减去1或数组中的最后一个索引值.
You need to assign i initially to the length minus one, or the last index value in the array.
for(i = myAnimal.length()-1; i >= 0; i--){
cout << myAnimal.at(i) << endl;
}
这篇关于C ++使用for循环反向打印字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文