C++ 'std::out_of_range'

标签 c++ error-handling

<分区>

我正在尝试使用链表打开测试文件。部分代码是这样的

#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
#include <list>
#include <iomanip>
#include <stdexcept>
using namespace std;

class isbn
{
    private:
    string code;
    int digit;

    public:
        //constructor
        isbn(): code(""), digit(0) { }

        //copy constructor
        isbn(const isbn &other):
        code(other.code),
        digit(other.digit) 
        {
            for(unsigned int i=0; i < (unsigned int) digit; i++)    
                code[i] = other.code[i];
        }
        void setCode(const char &temp);
        void setDigit(const int &num);

        isbn operator = (const isbn &other)
        {
            code = other.digit;
            digit = other.digit;
            for(unsigned int i=0; i < (unsigned int) digit; i++)    
            code[i] = other.code[i];
            return *this;
        }

};

void isbn::setCode(const char &temp)
{
    code = temp;
}
void isbn::setDigit(const int &num)
{
    digit = num;
}

void extIsbn_in_file(list<isbn> &isbns, const string &filename)
{
    ifstream filein;
    filein.clear();
    filein.open(filename.c_str());
    if(!filein)
    {
        cout << "error \n";
        exit(0);
    }
    cout << "\n";

    string contents;
    isbn aisbn;
    list<isbn>::iterator isbnitr;
    isbnitr = isbns.begin();
    int count = 0;

    while(!filein.eof())
    {
        getline(filein, contents, '\n');
        aisbn.setCode(contents.at(count));
        aisbn.setDigit(count);
        isbns.push_back(aisbn);
        count++;

    ..<more code>......
    ..<more code>......

    }
    filein.close();
}

int main(int argc, char *argv[])
{
if(argc > 0)
{
if(argc != 2)
{
cout << "invalid number of argument!! \n";
exit(0);
}
list<isbn> code;
extIsbn_in_file(code, argv[1]);
}
else
{
cout << "invalid number of argument!! \n";
exit(0);
}
return 0;
}

调用给定行时肯定会出现问题

        aisbn.setCode(contents.at(count));

在这段代码中,调用了 at 方法,但不太确定我做错了 setCode() 还是尝试使用 at()

错误说 什么(): basic_string::at 有什么想法吗?

最佳答案

我感觉到变量count即将超出索引。 只需检查 if(count < contents.size())打电话前 aisbn.setCode

我看到代码中的其他缺陷,你正在推送相同的 aisbn一次又一次反对isbns ( isbns.push_back(aisbn) )

关于C++ 'std::out_of_range',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16050537/

相关文章:

c++ - 针对 musl 和 glibc 将数据/时间转换为 tm/time_point。一般的方法

c++ - 重新配置现有对象而不是替换它们的循环缓冲区?

c++ - 覆盖 >> 像 int 这样的运算符

javascript - 如何测试抛出新的错误JavaScript

java - 在 Java 中防止异常与捕获异常

c++ - 静态字段链接器错误

c++ - libcurl 是否支持发送不加密的电子邮件?

actionscript - ActionScript拖放类型错误: Error #1009

python - 使用Flask错误处理程序立即捕获所有Werkzeug异常

vb.net - 我想在调用函数返回错误时控制错误消息