[英]out of range error when trying to read from a file?
我正在嘗試創建一個程序,其中從.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;
}
}
錯誤來自:
vector<Student> vi; // an empty vector
readStudent>>vi[i]; // oops, try to access out of bounds
當向量具有N
元素時,有效索引為0
到N - 1
。 當它為空時,您根本不能使用[]
。
要插入向量中,請使用push_back
成員函數。 另外,您還應該檢查流提取器是否成功。 您可以在main()
中用一塊石頭殺死兩只鳥:
Student temp;
while ( readStudent >> temp )
vi.push_back(temp);
而且你根本不需要i
。 之后,您可以使用vi.size()
來查明您閱讀了多少書。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.