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

字符串反转赋值遇string subscript out of range错误,求解决方案

Fixing the "string subscript out of range" Error in Your String Reversal Code

Hey there! Let's break down why you're hitting that string subscript out of range error and how to fix it.

The Root Cause

When you initialize string b;, it starts as an empty string with a size of 0. In your loop, you're trying to assign values to b[i] directly—but since b has no allocated space for those characters yet, accessing b[i] is out of bounds. Unlike some other languages, C++'s std::string doesn't automatically expand when you use the [] operator; you have to make sure the string has enough space first.

Solution 1: Pre-allocate Space for b

Before your loop, use resize() to give b the same length as a. This ensures there's a valid spot for every character you want to assign:

#include <iostream>
using namespace std;
int main() {
    string a, b;
    cin >> a;
    // Resize b to match a's length so we can safely use []
    b.resize(a.size());
    for (int i = 0; i < a.size(); i++) {
        b[i] = a[a.size() - 1 - i];
    }
    cout << b;
}

Solution 2: Use push_back() to Build b

Instead of pre-allocating space, you can use push_back() to add characters to the end of b one by one. This method automatically expands the string's size as needed, so you don't have to worry about bounds at all:

#include <iostream>
using namespace std;
int main() {
    string a, b;
    cin >> a;
    for (int i = 0; i < a.size(); i++) {
        // Add each reversed character to the end of b
        b.push_back(a[a.size() - 1 - i]);
    }
    cout << b;
}

A Quick Note on "No Built-in Functions"

Since you mentioned wanting to avoid built-in reversal tools (like std::reverse), both solutions above stick to basic string operations without using specialized reversal functions. The resize() and push_back() methods are core std::string members that just handle space management—they don't do any of the reversal work for you, which fits your goal perfectly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:52:31