用递归的方法,将输入的宇符串逆序输出。 (main 函数一>fuc函数)
时间: 2024-05-01 07:23:46 浏览: 13
以下是使用递归方法实现字符串逆序输出的代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
void reverse(string str){
if(str.length() == 0) // 当字符串长度为0时,递归结束
return;
else{
reverse(str.substr(1)); // 递归调用
cout << str[0]; // 输出第一个字符
}
}
int main(){
string s;
cout << "请输入一个字符串:";
cin >> s;
cout << "逆序输出为:";
reverse(s);
return 0;
}
```
该代码首先定义了一个 `reverse` 函数,该函数的参数是一个字符串 `str`。在函数中,首先判断字符串是否为空,若为空则递归结束;否则,将字符串从第二个字符开始截取,并将其作为参数再次调用 `reverse` 函数,直到字符串长度为0为止。最后,输出字符串的第一个字符。
在 `main` 函数中,先输入一个字符串,然后调用 `reverse` 函数进行逆序输出。