尝试从文件读取时超出范围错误?

时间:2014-11-01 01:01:01

标签: c++ c++11

我正在尝试创建一个程序,从.txt文件中读取三个变量(姓氏,UIN及其GPA)。程序编译但是当我尝试运行它时,它会给我一个超出范围的错误。有人可以告诉我这种情况发生的原因或为什么会在我的程序中发生这种情况?

    #include "std_lib_facilities_4.h"

struct Student{

private:
    string last_name;
    int UIN;
    double GPA;

public: 

    Student(string l_name, int number, double grade): last_name(l_name), UIN(number), GPA(grade){}
    string getlast_name() const{return last_name;}
    int getUIN() const {return UIN;}
    double getGPA() const{return GPA;}

};

istream &operator >>(istream &in, Student &student){
string last_name;
int UIN;
double GPA;
char c1, c2;
in>>last_name>>UIN>>GPA;
student = Student{last_name, UIN, GPA};
return in;
}

ostream &operator <<(ostream &out, const Student &student){
return out<<student.getlast_name()<<" "<<student.getUIN()<<" "<<student.getGPA();
}

int main(){
vector<Student>vi;
int i = 0;

ifstream readStudent;
readStudent.open("student.txt");
while (readStudent.good()){
    readStudent>>vi[i];
    ++i;
}

for(i=0; i<3; i++){
cout<<vi[i]<<endl;
}
}

1 个答案:

答案 0 :(得分:2)

错误来自:

vector<Student> vi;    // an empty vector

readStudent>>vi[i];    // oops, try to access out of bounds

当向量具有N个元素时,有效索引为0N - 1。如果它是空的,则根本不能使用[]

要插入向量,请使用push_back成员函数。您还应检查流提取器是否成功。你可以在main()中一石二鸟:

Student temp;

while ( readStudent >> temp )
    vi.push_back(temp);

您根本不需要i。之后您可以使用vi.size()来查看您阅读的数量。