Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ libc++;abi.dylib:终止时出现std::out_of_range类型的未捕获异常:基本_字符串错误?_C++ - Fatal编程技术网

C++ libc++;abi.dylib:终止时出现std::out_of_range类型的未捕获异常:基本_字符串错误?

C++ libc++;abi.dylib:终止时出现std::out_of_range类型的未捕获异常:基本_字符串错误?,c++,C++,我正在编写一个函数,它接收由空格分隔的字符串,并将每个单词添加到数组中。我一直收到一个错误,上面写着“libc++abi.dylib:终止时出现std::out_of_range:basic_string类型的未捕获异常。”我似乎找不到错误是什么 void lineParser(string line, string words[]) { string word = ""; int array_index = 0; int number_of_words = 1;

我正在编写一个函数,它接收由空格分隔的字符串,并将每个单词添加到数组中。我一直收到一个错误,上面写着“libc++abi.dylib:终止时出现std::out_of_range:basic_string类型的未捕获异常。”我似乎找不到错误是什么

void lineParser(string line, string words[])
{
    string word = "";
    int array_index = 0;
    int number_of_words = 1;
    int string_index = 0;
    while (string_index < line.length())
    {
        if (line.substr(string_index,1) != " ")
        {
            int j = string_index;
            while (line.substr(j,1) != " ")
            {
                word += line.substr(j,1);
                j++;
            }
            words[array_index] = word;
            array_index++;
            word = "";
            number_of_words++;
            string_index = j;
        }
        else
        {
            string_index++;
        }
    }
}
void行分析器(字符串行,字符串字[])
{
字串=”;
int数组_索引=0;
整字数=1;
int string_index=0;
while(字符串索引
在访问
单词时,您没有进行数组边界检查。如果传入的数组没有分配足够的空间,则运行时将超过数组的末尾


正如您在下面指出的,这不一定是问题所在,但是如果不查看其余的代码(例如main代码),就不可能这么说。这也是非常糟糕的代码,你永远不应该仅仅假设你知道数组的长度。您使用C++,使用STL容器。它将为您节省与数组相关的数不清的麻烦。

您的变量
j
也可以在不进行边界检查的情况下增加。它最终将超过用作索引的字符串的长度(
.line.substr(j,1)


一个非常糟糕的答案是在搜索
'
字符之前在字符串
行的末尾添加一个空格。一个更好的答案是在调用任何函数之前根据字符串的长度检查j,该函数使用它作为索引来访问字符串中的字符。

您应该将对可调整大小的容器(如std::vector)的引用传递给您的函数,而不是数组指针。因此,在main中执行此操作时不包括这个问题吗?常数int SIZE=5;字符串值[大小];我明白了。非常感谢你!很抱歉,我是这个网站的新手。我现在已把你的答案定为正确。