c++ - 如何修复 'std::logic_error' what(): basic_string::_M_construct null not valid 错误?
问题描述
我正在尝试检查输入字符串是字母数字还是更大写或为空。如果输入字符串在上述出现故障的字符串中,我只想返回 false/0 否则可以与运行正常的程序的其余部分一起工作。我的程序块有问题:
std::string myfunc(std::string input){
std::string b="";
if (!input.size()) return 0;
for (int i = 0; i < input.size(); i++){
if ( input[i] < 'a' || input[i] > 'z'|| isalpha(input[i]) || isupper(input[i]) ) return 0;
}
b = input;
//just copy the input string for now.
return b;
}
我称这个函数为
int main(){
std::string input="Somthing";
std::cout << myfunc(input)<< std::endl;
return 0;
}
得到以下错误?
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Aborted (core dumped)
没有这两种极端情况,该程序运行良好。我无法理解错误并找到解决方法?关于我做错了什么有什么建议吗?
解决方案
问题是您的函数中的两个return 0;
语句。该函数返回 a std::string
,它没有接受 aint
作为输入的构造函数。但是,它确实有一个接受const char *
指针的构造函数,0 可以隐式转换为。但是,std::string
使用空char *
指针构造 a 是未定义的行为,并且您的实现选择抛出std::logic_error
您在代码中未捕获的异常。
在这种情况下,我会简单地返回一个空白字符串:
std::string myfunc(const std::string &input){
if (input.empty()) return "";
for (int i = 0; i < input.size(); ++i){
char ch = input[i];
if ( !((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) ) return "";
}
return input;
}
然后调用者可以检查返回值是否为空,如果它想要:
if (myfunc(input).empty())
// error, do something
else
// OK, do something else
bool
使用返回 a而不是a 的函数会更好地服务std::string
:
bool isvalid(const std::string &input){
if (input.empty()) return false;
for (int i = 0; i < input.size(); ++i){
char ch = input[i];
if ( !((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) ) return false;
}
return true;
}
// if you still needed this function for something...
std::string myfunc(const std::string &input){
if (!isvalid(input)) return "";
return input;
}
if (!isvalid(input))
// error, do something
else
// OK, do something else
推荐阅读
- python - 无法使用 opencv minAreaRect 获取对象的边界
- ios - 实现多个 UITableViews 的最佳方式
- swift - 带有 jonkykong cocoapod 问题的侧边菜单栏
- php - 创建两个数组之间的关系
- vhdl - 制作串行输入串行输出加法器
- ios - 未找到科尔多瓦护理人员 Info.plist
- authentication - Skype For Business Online 身份验证错误 - 403 权限被拒绝
- python - 按空格键时如何播放音乐?
- javascript - 通过 Axios 发送一个 post 请求是在 Spring-Boot 后端生成一个空的 RequestBody。在 Postman 中工作,但不能通过 Axios 发布请求
- linux - 如何组装 ARB 组件