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

提取字符串纯字母时触发std::out_of_range错误,求解决

问题描述

我在各处都找不到解决方案,因此前来求助。以下是我的C++代码:

#include <iostream>
using namespace std;
  

int main()
{
    string napis;
    string new_napis = "";

    cout << "Give string: " << endl;
    cin >> napis;
    int length = napis.length();

    string search = "pies";
    size_t position = napis.find(search);

    if (position != string::npos){
        cout << "Found on position: " << position << endl;
    } else {
        cout << "Not found" << endl;
    }

    for (int i = 0; i <= length; i++){
       if (napis[i] > 96 && napis[i] < 123){
         new_napis.insert(i, 1, napis[i]);
       } else {
            cout << "";
       }
    }
    
    cout << "string without numbers: " << new_napis;
    
    


    return 0;
}

运行时出现如下错误:

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::insert: __pos (which is 1) > this->size() (which is 0)

我的需求是从输入字符串中提取仅小写字母,移除数字等其他字符生成新字符串。我曾尝试将循环条件i <= length修改为i = length,但没有效果,只是原样复制旧字符串。

问题分析与解决

错误原因

  1. 插入位置越界:new_napis初始为空字符串,使用insert(i, 1, napis[i])时,插入位置i不能超过当前字符串的长度。比如当i=1时,new_napis长度仍为0,直接触发越界异常;即便后续有字符插入,原字符串中若存在不符合条件的字符,new_napis的长度也不会随i同步增长,依然会出现插入位置大于字符串长度的情况。
  2. 循环条件错误:字符串索引从0开始,最大有效索引为length-1,i <= length会访问napis[length],属于越界访问,可能引发未定义行为。

修正方案

提取小写字母无需使用insert,直接用+=将符合条件的字符追加到new_napis末尾即可,同时修正循环条件避免越界:

#include <iostream>
using namespace std;
  

int main()
{
    string napis;
    string new_napis = "";

    cout << "Give string: " << endl;
    cin >> napis;
    int length = napis.length();

    string search = "pies";
    size_t position = napis.find(search);

    if (position != string::npos){
        cout << "Found on position: " << position << endl;
    } else {
        cout << "Not found" << endl;
    }

    // 修正循环条件为i < length,避免越界访问
    for (int i = 0; i < length; i++){
       if (napis[i] > 96 && napis[i] < 123){
         new_napis += napis[i]; // 直接追加字符到新字符串末尾
       }
       // 不符合条件的字符直接跳过,无需额外操作
    }
    
    cout << "string without numbers: " << new_napis << endl;
    
    return 0;
}

优化建议

用ASCII码范围判断小写字母虽然可行,但更推荐使用标准库的islower函数(需包含<cctype>头文件),代码可读性更强,且能兼容不同字符集:

#include <iostream>
#include <cctype> // 引入islower函数的头文件
using namespace std;
  

int main()
{
    string napis;
    string new_napis = "";

    cout << "Give string: " << endl;
    cin >> napis;
    int length = napis.length();

    string search = "pies";
    size_t position = napis.find(search);

    if (position != string::npos){
        cout << "Found on position: " << position << endl;
    } else {
        cout << "Not found" << endl;
    }

    for (int i = 0; i < length; i++){
       // 将字符转为unsigned char,避免islower处理负值时的未定义行为
       if (islower(static_cast<unsigned char>(napis[i]))){
         new_napis += napis[i];
       }
    }
    
    cout << "string without numbers: " << new_napis << endl;
    
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:35:11