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
Instead of
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;
}
write
for ( string::size_type i = 0; i < myAnimal.length(); i++ ){
cout << myAnimal.at(i) << endl;
}
// This one isn't executing
for ( string::size_type i = myAnimal.length(); i != 0; ){
cout << myAnimal.at( --i) << endl;
}
In your code you try to access an element of the string that is beyond the acceptable range that is equal to [0, length() - 1]
Also instead of type int it is better to use the type that std::string provides for the return type of member function length that is std::string::size_type.