You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置char[]实现输入任意字符数字均可正常输出并反转字符串

现有代码的核心问题

  • 栈上定长数组char a[80]最大只能存79个有效字符,输入超出长度就会触发缓冲区溢出,引发未定义行为
  • 用cin >> a读取输入时,遇到空格、制表符、换行符就会终止读取,无法处理带空格的字符串

推荐解决方案:改用C++标准库std::string

完全不需要手动设置固定长度的char数组,std::string会自动根据输入内容扩容,天然支持任意长度的字符、数字、特殊字符输入,还可以直接读取带空格的整行内容。修改后的完整代码如下:

#include <iostream>
#include <string>
using namespace std;

void reverse(string& str) {
    int len = str.size();
    for (int i = 0; i < len / 2; i++) {
        char temp = str[i];
        str[i] = str[len - i - 1];
        str[len - i - 1] = temp;
    }
}

int main()
{
    string a;
    cout << "\n Enter text:";
    // 读取整行输入,支持包含空格的内容
    getline(cin, a);
    cout << "\n The original string is:" << a << endl;
    reverse(a);
    cout << "\n The modified string is:" << a << endl;
    return 0;
}

必须使用char数组的实现方案

如果业务要求必须用char数组实现,就需要动态申请堆内存适配输入长度,用完后手动释放避免内存泄漏,代码示例如下:

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
void reverse(char str[], int l);
int main()
{
    // 先读取输入内容确定长度
    char temp_buf[1024];
    cout << "\n Enter text:";
    cin.getline(temp_buf, 1024);
    int length = strlen(temp_buf);
    // 动态申请char数组,长度+1存储字符串结束符'\0'
    char* a = new char[length + 1];
    strcpy(a, temp_buf);
    cout << "\n The original string is:";
    puts(a);
    reverse(a, length);
    cout << "\n The modified string is:";
    puts(a);
    // 释放动态申请的堆内存
    delete[] a;
}
void reverse(char str[], int l)
{
    char temp;
    for (int i = 0; i < l / 2; i++) {
        temp = str[i];
        str[i] = str[l - i - 1];
        str[l - i - 1] = temp;
    }
}

注意

不要尝试定义超大栈上char数组(例如char a[100000]),栈空间本身容量有限(通常仅几MB),申请过大容易触发栈溢出,且依然无法适配任意长度的输入需求。

内容的提问来源于stack exchange,提问作者Shubham Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 17:48:03