C++ - 尝试使用字符串函数来反转输入字符串

1 c++ string reverse namespaces

作为家庭作业的一部分,我需要能够使用输入字符串并使用字符串函数列表以多种方式操作它.第一个函数接受一个字符串并使用for循环将其反转.这就是我所拥有的:

#include <iostream>
#include <string>

namespace hw06
{
    typedef std::string::size_type size_type;

    //reverse function
    std::string reverse( const std::string str );

}


// Program execution begins here.

int main()
{
    std::string inputStr;

    std::cout << "Enter a string: ";
    std::getline( std::cin, inputStr );


    std::cout << "Reversed: " << hw06::reverse( inputStr )
    << std::endl;


    return 0;
}


//reverse function definition

std::string hw06::reverse( const std::string str )
{

    std::string reverseStr = "";
//i starts as the last digit in the input. It outputs its current 
//character to the return value "tempStr", then goes down the line
//adding whatever character it finds until it reaches position 0
    for( size_type i = (str.size() - 1); (i >= 0); --i ){
        reverseStr += str.at( i );
    }
        return reverseStr;
}
Run Code Online (Sandbox Code Playgroud)

程序要求输入,然后返回此错误:

在抛出'std :: out_of_range'的实例后调用终止what():basic_string :: tat

我真的不知道我在这里做错了什么.循环似乎对我来说是正确的,所以我误解了如何引用该函数?

Jer*_*fin 5

除非你真的编写一个循环,它可能更容易只是像做:

std::string reverse(std::string const &input) { 
    return std::string(input.rbegin(), input.rend());
}
Run Code Online (Sandbox Code Playgroud)