如何修复“std::logic_error” what(): basic_string::_M_construct null not valid 错误?

anu*_*anu 2 c++

我正在尝试检查输入字符串是字母数字还是大写或空。如果输入字符串在上述出现故障的字符串中,我只想返回 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;
}
Run Code Online (Sandbox Code Playgroud)

我把这个函数称为

int main(){
    std::string input="Somthing";
    std::cout << myfunc(input)<< std::endl;
    return  0;
}
Run Code Online (Sandbox Code Playgroud)

收到以下错误?

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)

该程序在没有这两个边缘情况的情况下运行良好。我无法理解错误并找到解决方法?关于我做错了什么的任何建议?

Rem*_*eau 7

问题在于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;
}
Run Code Online (Sandbox Code Playgroud)

然后调用者可以检查返回值是否为空,如果它想:

if (myfunc(input).empty())
    // error, do something
else
    // OK, do something else
Run Code Online (Sandbox Code Playgroud)

使用返回 abool而不是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
Run Code Online (Sandbox Code Playgroud)