String抛出Vector Subscript Debug Assertion

时间:2018-02-12 12:27:58

标签: c++ string visual-c++ vector

所以我试图从文本文件中读取时间并从每个条目中取出标题行。

该文件格式为

  

董事会编号#15
    2月06日10:00
    2月06日11:00
    董事会编号#12 ......

每个电路板都有不同数量的条目。为此,我使用以下代码

int main()
{
    fstream log_file;
     //get the dat file
    std::vector <TFile*> files;
    std::vector <std::string> t, fnames;
    int bn[4], nruns[4];
    fstream runtimes;
    std::string line; 
    runtimes.open("runlogs.txt");
    int i = 0;
    while (!runtimes.eof() && runtimes.is_open()) {
        while (getline(runtimes, line)) {
            try {
                std::cout << line << std::endl;
                if (line.find("#") != std::string::npos) {
                    std::istringstream templine(line);
                    std::string temp;
                    while (getline(templine, temp, ' ')) {
                        try {
                            stof(temp);
                            fnames.push_back(temp);
                            i++;
                        }
                        catch (std::exception& e) {
                            continue;
                        }
                    }
                }
                else {
                    t.push_back(line);
                    //std::cout << line << std::endl;
                    nruns[i - 1]++;
                }
            }
            catch (std::exception& e) {
                            std::cout << "error of form: " << e.what() << std::endl;  
            }

我的问题是该程序抛出了一个调试断言错误,没有输出。这让我感到困惑,因为它抛出的错误是一个超出范围断言的向量下标。

EDIT ::调试器提供以下输出:

Screen shot of the debugger at break

通过调试后,它继续在第一个输出之前,引用向量include中的相同行。我也已经修复了nruns的潜在问题,但这根本没有改变它。调试也会抛出异常

  

0x0F4A0B45(ucrtbased.dll)的未处理异常

1 个答案:

答案 0 :(得分:0)

问题是runtimes.is_open()。当它被删除,并简单地用!eof()替换它时就没有了。文件名实际上是错误的,但现在它在文件末尾有类似的问题。

编辑:在修复文件名,然后返回并重新检查某些值时,一行运行时调用的文件之一已损坏。添加了try / catch块,并修复了文件末尾的行为,现在工作正常。谢谢你的帮助,抱歉打扰你这么简单的事情,还在学习方法。