我正在尝试检查输入字符串是字母数字还是更大写或为空。如果输入字符串在上述出现故障的字符串中,我只想返回 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)
没有这两种极端情况,该程序运行良好。我无法理解错误并找到解决方法?关于我做错了什么有什么建议吗?
原文由 Anu 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题是您的函数中的两个
return 0;
语句。该函数返回一个std::string
,它没有接受int
作为输入的构造函数。但是,它确实有一个构造函数接受const char *
指针,0 可以隐式转换为。但是,使用空char *
指针构造std::string
是 未定义的行为,并且您的实现选择抛出std::logic_error
您的代码未捕获的异常.在这种情况下,我会简单地返回一个空白字符串:
然后调用者可以检查返回值是否为空,如果它想要:
使用返回
bool
而不是std::string
的函数会更好地服务: