首页 > 解决方案 > C++ 字符串连接有时会失败

问题描述

我是 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 */
    }

奇怪的是,如果缺少.in ,代码可以正常工作。".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";

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

标签: c++stringconcatenation

解决方案


谢谢你们的评论!你激励我再看一遍所有的东西,所以我发现了我的错误。在一个只有 64 个位置的数组中设置第 65 个位置是一个简单的尝试。

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

我仍然不明白,为什么在第 71 个索引而不是第 65 个索引处引发异常,以及为什么它发生在字符串连接而不是数组操作中,但至少代码现在似乎可以工作。


推荐阅读