[英]Parsing a text file in c++ and storing strings in separate variables
I have a text file that will be something like this. 我有一个文本文件,像这样。
lastname firstname, id
I want to go through the text file and add each record into a single vector that has 3 variables: lastname, firstname, id
我想遍历文本文件并将每个记录添加到具有3个变量的单个向量中: lastname, firstname, id
Here is the code I'm using, but for some reason I don't get the output I want. 这是我正在使用的代码,但是由于某种原因,我没有得到想要的输出。
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
}
This is the function I'm using to display the records in the vector. 这是我用来在向量中显示记录的功能。
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;
}
}
I guess, you are actually constructing an ifstream
object but not opening the file to perform input operations on it. 我猜想,您实际上是在构造ifstream
对象,而不是打开文件以对其执行输入操作。 You are missing the second parameter of the ifstream
object construction , which actually opens the file as if the call is made to open the file. 您缺少ifstream
对象构造的第二个参数,该参数实际上打开了文件,就像调用了打开文件一样。 So try - 所以尝试-
ifstream infile("spring2011.txt", ifstream::in );
or 要么
ifstream infile;
infile.open ("spring2011.txt", ifstream::in);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.