如何修复 '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)

没有这两种极端情况,该程序运行良好。我无法理解错误并找到解决方法?关于我做错了什么有什么建议吗?

原文由 Anu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 4.6k
2 个回答

问题是您的函数中的两个 return 0; 语句。该函数返回一个 std::string ,它没有接受 int 作为输入的构造函数。但是,它确实有一个构造函数接受 const char * 指针,0 可以隐式转换为。但是,使用空 char * 指针构造 std::string未定义的行为,并且您的实现选择抛出 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 而不是 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

原文由 Remy Lebeau 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果要返回 false(或 true),则应将函数的返回类型更改为 bool

 bool myfunc(std::string input) {
^^^^

其次,如果您要返回 false 那么这就是您应该返回的

if (!input.size()) return false;
                          ^^^^^

从布尔函数返回 0 不是错误,因为 0 会自动转换为 false,但显然在风格上更好地表达你的意思。

原文由 john 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题