繁体   English   中英

在C ++中解析文本文件并将字符串存储在单独的变量中

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM