为每个使用内部字符串时运行时错误
Runtime error while using string inside for each
在此代码中,我收到以下运行时错误:
在抛出"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::string
的find()
函数在找不到搜索字符串时返回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
的变量用于检查找到字符串时该怎么做。如果找不到字符串,我将返回输入文本本身。
为了更好的可读性,我更改了函数和变量名称。
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 如何修复我的字符串以避免运行时错误?
- 字符串::插入产生运行时错误
- 为什么此代码使用带有字符串(C )的MAP具有运行时错误
- C++:将字符串流转换为 char* 运行时错误
- 在VC2010中使用Char数组显示字符串时发生运行时错误
- 使用字符串向量初始值设定项时,我收到运行时错误"terminate called after throwing instance of `std::length_error`"
- 为每个使用内部字符串时运行时错误
- 反向字符串脚本给出运行时错误
- C++ 中的运行时错误字符串声明
- 字符串程序C++运行时错误
- 打印字符串时出现运行时错误,即使它在函数中运行良好
- 函数从字符串转换为int时出现运行时错误
- 使用 cout 打印字符串时C++代码块中的运行时错误<<
- 当使用字符串时,c++程序给出一个运行时错误
- c++ char*转字符串运行时错误
- c++运行时错误中的字符串
- 运行时错误反转字符串