为每个使用内部字符串时运行时错误

Runtime error while using string inside for each

本文关键字:字符串 运行时错误 内部      更新时间:2023-10-16

在此代码中,我收到以下运行时错误:

在抛出"std::out_of_range"
实例后终止调用 what(): basic_string::替换 bash: 第 1 行: 9471 中止
(核心倾倒)

就我而言,这意味着我已经在每个循环中操作了向量,而我没有这样做。

#include <iostream>
#include <string>
#include <vector>

std::string replace(std::string text,
                  std::string find,
                  std::string replace)
{
    return(text.replace(text.find(find), find.length(), replace));
}
int main()
{
    std::vector<std::string> mylist={"col1","cell2","col3","cell4","col5"};
    for(const std::string item: mylist)
    {
        std::cout<<replace(item,"cell","item")<<std::endl;
    }
    return 0;
}

您正在尝试将cell替换为字符串col1中的item。没有这样的子字符串,所以text.find()将返回string::npos(通常((size_t) -1),但特定于实现)。之后,string::npos传递给replace(),从而导致异常。

像这样重写你的函数:

std::string replace(std::string text,
                std::string find,
                std::string replace)
{
    size_t idx = text.find(find);
    if(idx == std::string::npos)
        return(text);
    return(text.replace(idx, find.length(), replace));
}

std::stringfind()函数在找不到搜索字符串时返回npos位置。这个npos位置不能用于replace()并给出此错误。

这是一个克服运行时错误的程序:

#include <iostream>
#include <string>
#include <vector>

std::string replaceText(std::string text,
    std::string f,
    std::string r)
{
    size_t found = text.find(f);
    if (found != std::string::npos)
        return(text.replace(found, f.length(), r));
    return text;
}
int main()
{
    std::vector<std::string> mylist = { "col1", "col2", "col3", "col4", "col5" };
    for (const std::string item : mylist)
    {
        std::cout << replaceText(item, "cell", "item") << std::endl;
    }
    return 0;
}

主要部分是:

int found = text.find(f);
if (found != std::string::npos)
    return(text.replace(text.find(f), f.length(), r));
return text;

其中一个名为 found 的变量用于检查找到字符串时该怎么做。如果找不到字符串,我将返回输入文本本身。

为了更好的可读性,我更改了函数和变量名称。