c++ - 字符串迭代器不可取消引用

标签 c++ visual-studio-2012

我正在使用一个库来解析 .pgn 文件,当我尝试运行该项目时,我发现了这个错误:Debug Assertion Failed!程序:C:\windows\SYSTEM32\MSVCP110D.dll 文件:c:\program files (x86)\microsoft visual studio 11.0\vc\include\xstring 线路:79 表达式:字符串迭代器不可取消引用 有关您的程序如何导致断言失败的信息,请参阅有关断言的可视化 C++ 文档。

问题是当迭代器到达文件末尾时,它没有指向任何东西(开始迭代器(itr1)==结束迭代器(itr2)),我尝试添加条件来检查itr1是否到达末尾的文件,但它是无用的。 所以请告诉我我的错在哪里。 这是我的代码 source.cpp 文件:

#include <iostream>
#include <fstream>
#include <PGNGameCollection.h>
int main()
{
    std::ifstream pgnfile("sample.pgn");
    pgn::GameCollection games;
    pgnfile >> games;
    std::cout << "the file sample.pgn contains " << games.size() << "games"     << std::endl;
    system("pause");
    return 0;
}

这是导致错误的类函数:

bool pgn::Parser::getComment(std::string::const_iterator &itr1, const std::string::const_iterator &itr2, pgn::CommentText &out)
{
    std::string::const_iterator local_itr=itr1;
    std::string comment;
    if(*local_itr != '{')
        return false;
    local_itr++; //skipping '{'

    while((*local_itr != '}') && (local_itr != itr2))
    {
        comment += *local_itr++;
    }
    local_itr++; //skipping '}'
    skipBlanks(local_itr, itr2);
    itr1=local_itr;
    out=pgn::CommentText(comment);
    return true;
}

skipBlanks 函数:

void pgn::Parser::skipBlanks(std::string::const_iterator &itr1, cost std::string::const_iterator &end)
{
    while((itr1 != end) && (isspace(*itr1)))
    {
        itr1++;
    }
}

我已经在 stackoverflow 和 google 上搜索了所有类似的问题,但我找不到答案。我还逐行跟踪代码,直到找到导致错误的函数。

最佳答案

如果 itr2 是您的结束迭代器,那么您必须在尝试取消引用它之前检查您的迭代器的结束条件

while((local_itr != itr2) && (*local_itr != '}'))

你反其道而行之,这肯定会导致你所描述的问题。

在函数的最开头添加结束条件检查可能也很有意义,因为在那里您也取消了对 local_itr 的引用。

另外,如果你的循环因为 local_itr 到达 itr2 而终止,并且 itr2 和之后没有任何东西,那么循环之后的代码没有意义。在这种情况下,您不允许增加 local_itr

关于c++ - 字符串迭代器不可取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39923411/

相关文章:

c++ - -g++ 中的 Wsign-compare 警告

c++ - Linux : Qt Creator debugger hangs while QQmlApplicationEngine is created

c - 带有 CUDA 5.5 的 Visual Studio 2012 - 无法识别 CUDA 语法和定义

.net - 如何使用 Visual Studio 2012 在 XP 上定位 .NET 4.0.3?应用程序无法运行,错误代码为 "not a valid Win32 application"

c++ - VS2012 寻找 64 位 dll 而不是 32 位

c++ - 如何处理 !address -filter Windbg

c++ - 执行名称输入时 while 循环退出太快

visual-studio - 是否有热键可固定/自动隐藏诸如解决方案资源管理器之类的面板?

c++ - 使用较旧版本的 MFC 和较新版本的 Visual Studio

c++ - 引用一个不存在的变量将是一个错误,但为什么这不会导致任何错误呢?