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

C++使用insert函数在字符前加空格:代码失效原因咨询

Why Your String Insert Code Isn't Working

Hey there, let's figure out why your code isn't behaving as expected—there are two critical issues tripping it up:

1. Out-of-Bounds Memory Access (Undefined Behavior)

Your loop runs i from 0 up to line.length() - 1 (since the condition is i < line.length()). The problem hits when i reaches the last valid index of the string (line.length() - 1): you try to access line[i+1], which is line[line.length()]—way beyond the string's valid bounds (C++ strings are 0-indexed, so the last character lives at index length()-1).

Accessing out-of-bounds memory triggers undefined behavior—this can cause your program to crash, spit out garbage values, or act unpredictably. For example, if your string is "x=y" (length 3), when i=2, i+1=3 is an invalid index.

2. Skipping Characters & Loop Length Chaos

When you call line.insert(i, " "), you add a space to the string, which increases its length by 1. But your loop keeps incrementing i normally, leading to two problems:

  • You'll skip over characters you need to check: after inserting a space, every character after i shifts right by 1. If you increment i by 1, you'll jump past the character that was originally at i+1.
  • The loop runs longer than intended: since line.length() grows each time you insert a space, your loop condition i < line.length() will keep the loop running more times than necessary, worsening the out-of-bounds issue.

Fixed Code Examples

Here are two solid fixes to resolve both problems:

Approach 1: Iterate Backwards (Cleanest)

By looping from the end of the string to the start, inserting spaces doesn't affect the indices of the characters you haven't checked yet:

for(int i = line.length() - 1; i >= 0; i--) { 
    if(line[i] == '=') { 
        line.insert(i, " "); // Add space right before the '='
    } 
}

Approach 2: Adjust Index When Inserting (Forward Loop)

If you prefer looping forwards, adjust the index after inserting to avoid skipping characters:

for(int i = 0; i < line.length();) { 
    // First check we won't go out of bounds
    if(i + 1 < line.length() && line[i+1] == '=') { 
        line.insert(i, " ");
        i += 2; // Skip the space we added and the '='
    } else {
        i++;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:37:55