C ++字符串连接有时会失败

时间:2018-12-01 13:47:42

标签: c++ string concatenation

我是C ++的血腥初学者。 我尝试读取序列号文件。为此,我必须创建字符串来包含带有升序文件索引的文件名。

我的代码适用于70以下的索引。当索引为71时,突然引发异常。

这是我的代码:

for (int i = 0; i < 110; i++)
{
    std::string index = std::to_string(i);
    std::string filenameA = "fileA"+ index + ".png"; // Here the Exception is thrown
    std::string filenameB = "fileB"+ index + ".png";
    std::string filenameC = "fileC"+ index + ".png";

    ...
}

i=71出现读取访问冲突。 通过以下方法将异常抛出到文件xutility中:

inline void _Container_base12::_Orphan_all() noexcept
    {   // orphan all iterators
 #if _ITERATOR_DEBUG_LEVEL == 2
    if (_Myproxy != nullptr)
        {   // proxy allocated, drain it
        _Lockit _Lock(_LOCK_DEBUG);

        for (_Iterator_base12 **_Pnext = &_Myproxy->_Myfirstiter;
            *_Pnext != nullptr; *_Pnext = (*_Pnext)->_Mynextiter)
            (*_Pnext)->_Myproxy = nullptr;
        _Myproxy->_Myfirstiter = nullptr; // Here the exception is thrown
        }
 #endif /* _ITERATOR_DEBUG_LEVEL == 2 */
    }

奇怪的是,如果缺少.中的".png",则代码可以正常工作。 另外,如果我更改文件的顺序,例如这样

std::string filenameB = "fileB"+ index + ".png";
std::string filenameC = "fileC"+ index + ".png";
std::string filenameA = "fileA"+ index + ".png";

错误仍然发生在std::string filenameA = "fileA"+ index + ".png";

我真的不明白,为什么在这种特殊情况下字符串连接失败。

1 个答案:

答案 0 :(得分:0)

感谢您的所有评论! 您启发了我再次审视所有内容,所以我发现了我的错误。 简单地尝试在只有64个位置的数组中设置第65个位置。

以前,此代码必须读取一组64个文件,现在我将其扩展为109个文件。 我只是忘了更新数组的大小,这会保存每个文件的信息。

我还是不明白,为什么异常在第71个索引处而不是第65个索引处抛出,为什么它在字符串连接处而不是在数组操作处发生,但是至少代码现在可以正常工作