【问题标题】:Parsing a text file in c++ and storing strings in separate variables在 C++ 中解析文本文件并将字符串存储在单独的变量中
【发布时间】:2011-07-12 06:29:28
【问题描述】:

我有一个类似这样的文本文件。

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;   
    }  
}       

【问题讨论】:

  • 代码缩进四个空格。 不要使用标签过去。
  • 到底出了什么问题?向量中没有存储任何内容吗?还是有其他问题?
  • 向量中没有存储任何内容,我得到一个带有学生姓名的文本文件,例如 Bob Marley, 011.... 我想浏览文本文件并将 Bob 添加到 fname,marely到 lname 和 011 到 id... 并将其推入向量中.... 在我希望能够访问向量并打印它之后,它会像这样打印:
  • 您应该尝试插入一些 cout,以便我们可以看到您实际读取和写入的内容。

标签: c++ parsing vector text-files


【解决方案1】:

我猜,您实际上是在构造一个ifstream 对象,但没有打开文件对其执行输入操作。您缺少 ifstream 对象构造的第二个参数,它实际上打开了文件,就好像调用打开文件一样。所以试试 -

ifstream infile("spring2011.txt", ifstream::in );

ifstream infile; 
infile.open ("spring2011.txt", ifstream::in);

【讨论】:

  • 我做到了,这就是我的输出。
  • 1.姓名:Hofnar Tudor 002 Wright Matthew 003,学号:但我希望它看起来像:1.姓名:Hofnar Tudor 学号:002 2.姓名:Wright Matthew
  • 复制文本文件 spring2011.txt 的内容与问题中的完全相同。
  • 但是他们在彼此之下,也就是说两个学生在两条不同的线上
  • @Angad Soni- 这是getline(infile,fname, ','); 之一以, 作为分隔符的错字吗?不应该是空格符吗?
猜你喜欢
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2015-10-13
  • 2011-09-07
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 2021-12-27
相关资源
最近更新 更多