[英]Parsing a text file in c++ and storing strings in separate variables
我有一個文本文件,像這樣。
lastname firstname, id
我想遍歷文本文件並將每個記錄添加到具有3個變量的單個向量中: lastname, firstname, id
這是我正在使用的代碼,但是由於某種原因,我沒有得到想要的輸出。
int Student::readStudents(vector<Student> &term){
ifstream infile("spring2011.txt");
if ( !infile ) {
cout << "Error attempting to open file ... "
<< "(Perhaps it dosen't exist yet?)" << endl;
return -1; // report error condition ...
}
term.clear(); // empty the student vector
string lname,fname, id;
int j;
while(infile){
getline( infile, lname, ' ');
getline(infile,fname, ',');
getline(infile, id, ' ');
term.push_back( Student(lname, fname, id) ); // construct and add new Student
j++;
}
infile.close();
return j; //count of records
}
這是我用來在向量中顯示記錄的功能。
void Student::showStudents(vector<Student> &term){
for( size_t i=0; i< term.size(); ++i ){
cout << i+1 << ".\n"
<< "Name : " << term[i].getLastName()<<", "<< term[i].getFirstName()<< endl
<< "Student Number : " << term[i].getId() << endl;
}
}
我猜想,您實際上是在構造ifstream
對象,而不是打開文件以對其執行輸入操作。 您缺少ifstream
對象構造的第二個參數,該參數實際上打開了文件,就像調用了打開文件一樣。 所以嘗試-
ifstream infile("spring2011.txt", ifstream::in );
要么
ifstream infile;
infile.open ("spring2011.txt", ifstream::in);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.