C++ Printing a string in reverse using a for loop

前端 未结 6 1618
别跟我提以往
别跟我提以往 2021-01-25 12:13

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

6条回答
  •  执念已碎
    2021-01-25 12:30

    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.

提交回复
热议问题