输入字符串(长度小于50),逆序输出该字符串cpp
时间: 2023-06-14 08:03:47 浏览: 44
可以使用 C++ 的字符串反转函数 `reverse()` 来实现字符串的逆序输出。具体代码如下:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s;
cin >> s;
reverse(s.begin(), s.end());
cout << s << endl;
return 0;
}
```
输入一个字符串,使用 `reverse()` 函数将字符串反转,然后输出即可。
相关问题
c++随机输入一个字符串,并逆序输出它
可以使用`std::getline`函数读取一行字符串,再使用`std::reverse`函数逆序输出。下面是示例代码:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str;
std::cout << "请输入一个字符串:" << std::endl;
std::getline(std::cin, str);
std::reverse(str.begin(), str.end());
std::cout << "逆序输出:" << str << std::endl;
return 0;
}
```
示例输出:
```
请输入一个字符串:
Hello, world!
逆序输出:!dlrow ,olleH
```
C++逆序输出字符串
以下是两种C++逆序输出字符串的方法:
1.使用for循环逆序输出字符串
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
for (int i = str.length() - 1; i >= 0; i--) {
cout << str[i];
}
return 0;
}
// 输出:dlrow olleh
```
2.使用reverse函数逆序输出字符串
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = "hello world";
reverse(str.begin(), str.end());
cout << str;
return 0;
}
// 输出:dlrow olleh
```