使用dwv-c++从键盘将一个字符串输入到字符数组str中,之后反序存放并输出。如,输入"Abcd e",则输出"e dcbA"。要求在同一个数组str中进行反序
时间: 2024-12-18 09:17:05 浏览: 55
在C++中,我们可以使用`std::cin`从键盘获取用户输入,并将其存储在一个字符数组中。然后通过遍历数组并将元素逐个插入到数组开头的方式来实现反序。以下是一个简单的示例程序:
```cpp
#include <iostream>
using namespace std;
void reverseArray(char str[], int length) {
for (int i = 0; i < length / 2; ++i) {
char temp = str[i];
str[i] = str[length - 1 - i]; // 交换位置
str[length - 1 - i] = temp;
}
}
int main() {
const int SIZE = 100; // 定义字符数组大小
char str[SIZE];
cout << "请输入一个字符串(不超过" << SIZE - 1 << "个字符): ";
cin.getline(str, SIZE); // 从键盘读取直到换行符
// 调整字符串长度,去掉末尾的换行符
str[strcspn(str, "\n")] = '\0';
int length = strlen(str); // 计算实际字符数
// 反转字符串
reverseArray(str, length);
cout << "反转后的字符串是: " << str << endl;
return 0;
}
```
阅读全文
相关推荐


















