c++ 在新字符串中插入数字会导致错误

j0pj023g  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(147)

我到处都找不到所以我来了

#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〈=长度可能是一个问题,但当我将其改为i =长度时,它没有做任何事情,只是复制粘贴旧字符串

xuo3flqw

xuo3flqw1#

有两个问题与您的代码的越界访问有关:
1.遍历napis的正确方法是从0length - 1,因此您需要做的检查是i < length
1.如果要通过insertnew_napis末尾添加新的非数字字符,则需要保留new_napis中字符的计数器,以用作insertpos参数。
Demo(https://godbolt.org/z/hdvYTqGq5)

#include <fmt/core.h>
#include <iostream>

int main() {
    std::string napis;
    std::string new_napis;

    std::cout << "Give string: \n";
    std::cin >> napis;
    int length = napis.length();
    fmt::print("{} ({})\n", napis, length);

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

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

    for (int i = 0, j = 0; i < length; i++) {
        if (napis[i] > 96 && napis[i] < 123) {
            new_napis.insert(j++, 1, napis[i]);
        }
    }

    std::cout << "string without numbers: " << new_napis;
}

// Outputs:
//
//   Give string: 
//   spe12cia34l (11)
//   Not found
//   string without numbers: special

创建new_napis的另一种方法是用途:

  • std::copy_if遍历napis并在满足 predicate 的情况下将字符复制到new_napis,以及
  • std::islower检查字符是否为小写字母。

Demo(https://godbolt.org/z/W3dPc6GPh)

#include <algorithm>  // copy_if
#include <cctype>  // islower

std::string new_napis;
std::ranges::copy_if(napis, std::back_inserter(new_napis),
    [](unsigned char c){ return std::islower(c); });

相关问题