c++随机输入一个字符串,并逆序输出它
时间: 2024-01-10 07:02:50 浏览: 126
可以使用`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
```
相关问题
顺序表的定义,初始化,插入,删除,并编写一个读入一个字符串,把它顺序存入一个顺序表并逆序打印出
顺序表是一种线性数据结构,它用一组连续的存储单元来存储数据元素,其特点是可以随机访问任何一个元素。
定义:顺序表可以用数组来实现,定义一个固定大小的数组作为顺序表的存储空间,并在数组中依次存放顺序表中的元素。
初始化:顺序表的初始化就是将其元素个数设置为0,即表为空。
插入:顺序表中的插入操作需要将插入位置后的元素全部向后移动一位,然后将要插入的元素放到指定位置。
删除:顺序表的删除操作需要将删除位置后的元素全部向前移动一位,然后将最后一个元素删除。
以下是一个读入一个字符串,把它顺序存入一个顺序表并逆序打印出的示例代码:
```C++
#include <iostream>
#include <string>
using namespace std;
const int MAXSIZE = 100; // 顺序表的最大长度
typedef struct {
char data[MAXSIZE]; // 顺序表的存储空间
int length; // 顺序表的当前长度
} SeqList;
// 初始化顺序表
void InitList(SeqList &L) {
L.length = 0;
}
// 插入元素
bool ListInsert(SeqList &L, int pos, char elem) {
if (pos < 1 || pos > L.length + 1 || L.length >= MAXSIZE) {
return false;
}
for (int i = L.length; i >= pos; i--) {
L.data[i] = L.data[i-1];
}
L.data[pos-1] = elem;
L.length++;
return true;
}
// 删除元素
bool ListDelete(SeqList &L, int pos) {
if (pos < 1 || pos > L.length) {
return false;
}
for (int i = pos; i < L.length; i++) {
L.data[i-1] = L.data[i];
}
L.length--;
return true;
}
int main() {
SeqList L;
InitList(L);
string str;
cout << "请输入字符串:";
getline(cin, str);
for (int i = 0; i < str.length(); i++) {
ListInsert(L, i+1, str[i]);
}
cout << "逆序输出:";
for (int i = L.length; i >= 1; i--) {
cout << L.data[i-1];
}
cout << endl;
return 0;
}
```
该程序首先定义了顺序表的结构体,并初始化了一个空的顺序表。接着通过 `getline()` 函数读取用户输入的字符串,并将其逐个插入到顺序表中。最后,通过循环逆序输出顺序表中的元素。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)