【问题标题】:Vector of structs and I don't know what to do结构向量,我不知道该怎么办
【发布时间】:2011-10-31 04:45:04
【问题描述】:

对于每一行文本:

-Get first name
-Get last name
-Get Student Number

(会有未知数量的行,每行的格式都相同。)
格式:

First Last 111111111
First Last 111111112
...

我想将每个学生的每一部分都放入自己的结构中。我已将结构设置如下:

struct Student{  
    string lastName;
    string firstName;
    string stdNumber;
    double assgn1;//doubles will be used later in prog.
    double assign2;
    double assign3;
    double assign4;
    double midTerm;
    double finalGrade;
};

我的文件输入功能如下:

int getFileInfo()
{       
    int failed=0;
    ifstream fin;   
    string fileName;    
    vector<Student> students;

    Student s;                  // A place to store data of one student
    cout<<"Please enter the filename of the student grades (ex. filename_1.txt)."<<endl;
    do{                                 
        if(failed>=1)                           
            cout<<"Please enter a correct filename."<<endl; 
        cin>>fileName;                              
        fin.open(fileName.c_str());// Open the file     
        failed++;                                           
    }while(!fin.good());                                        
    while (fin >> s.firstName >> s.lastName >> s.stdNumber)
        students.push_back(s);                      
    fin.close();                            
    return 0;                                   
}  

在文件输入中,我制作了一个向量,但我不确定如何访问它的每个单独部分,或者学生s,因为它似乎只制作一个学生。有人告诉我,文件的每一行都被拆分并输入到students 向量中,但我不知道如何提取该信息。如何让每个学生脱离students 向量并进入自己的结构,以便我可以将每个学生用作自己的结构? 所以最后,我希望能够输出:

Student1: First Last 111111111
Student2: First Last 111111112
However More students are in the file

提前感谢您的帮助!

@洛基 我改变了循环,所以loop != end,我仍然遇到同样的问题。这是我的代码:

int getFileInfo()
{
int failed=0;
ifstream fin;
string fileName;
vector<Student> students;// A place to store the list of students
vector<Student>::iterator loop = students.begin();
   vector<Student>::iterator end  = students.end();

Student s;                  // A place to store data of one student
cout<<"Please enter the filename of the student grades (ex. filename_1.txt)."<<endl;
do{
if(failed>=1)
    cout<<"Please enter a correct filename."<<endl;
    cin>>fileName;
    fin.open(fileName.c_str());// Open the file
    failed++;
}while(!fin.good());

 while (fin >> s.firstName >> s.lastName >> s.stdNumber){
    cout<<"Reading "<<s.firstName<<" "<<s.lastName<<" "<<s.stdNumber<<endl;
    students.push_back(s);
}
fin.close();

    for(loop;loop!=end;++loop)
    cout<<loop->firstName<<" "<<loop->lastName<<" "<<loop->stdNumber<<endl;

return 0;
}

Visual Studio 又说vector iterators incompatible
指向“C:\Program Files(x86)\Microsoft Visual Studio 10.0\vc\include\vector”

【问题讨论】:

  • 没什么花哨的。只需从文件中读取ifstream::read()每个结构并使用vector::push_back将其保存在向量中。
  • 我已经将数据从文本文件中删除并放入向量中。它正在从我遇到问题的结构向量中获取保存的数据。
  • 我添加了一个答案,希望对你有所帮助。
  • 请多花点功夫格式化输入。阅读网站的标记部分。 stackoverflow.com/editing-help。请注意,当您编辑/编写文本时,此链接可通过编辑框右上角的问号获得。meta.stackexchange.com/q/74999/138817
  • @LokiAstari 我会确保下次这样做。感谢您这次修复它!

标签: c++ vector struct io


【解决方案1】:

Online Demo Sample:

#include<iostream>     
#include<string>
#include<vector>

using namespace std;

struct Student
{
    string lastName;
    string firstName;
    string stdNumber;
    double assgn1;//doubles will be used later in prog.
    double assign2;
    double assign3;
    double assign4;
    double midTerm;
    double finalGrade;
};

int main()
{
    Student obj;
    obj.firstName = "ABC";
    obj.lastName = "XYZ";

    vector<Student> students;
    students.push_back(obj);
    vector<Student>::iterator it;

    cout << "students contains:";
    for ( it=students.begin() ; it != students.end(); ++it )
    {
        cout << " " << (*it).firstName;
        cout << " " << (*it).lastName;
        //And so on...
    }

        return 0;
}

【讨论】:

  • it &lt; students.end()?不应该是it != students.end()吗?另外,比起it++,更喜欢++it
  • @Nawaz:很好发现。实际上我正在编辑,但感谢您指出。
  • 感谢您的快速帮助! @Als 我在我的代码中尝试过并运行它,它给了我一个弹出窗口,上面写着"Debug Assertion Failed!" Expression: Vector iterator not dereferencable." Any Idea 这是什么意思?
【解决方案2】:

在文件输入中,我创建了一个向量,但我不确定如何访问它的每个单独部分。

您可以通过 operator[] 访问单个元素

students[0].firstName;  // get the first name.

std::cout << students[1].firstName; // prints out the first name.

您可以使用从 0 -> size() 的索引。

size_t  size = students.size();  // number of students in the vector.

students[size].firstName; // This is wrong. You expression in
                          // [] must be less than size as the elements are
                          // numbered from 0 to size() -1.

因为好像只招一个学生。

你只创建了一个学生的's'(作为一方没有选择更好的名字)。但是当您调用 push_back() 时,您正在将此学生对象复制到向量中。所以向量得到它存储的“s”的副本。然后每次通过循环时,您都会用从文件中检索到的新值覆盖“s”中的旧值。

我被告知文件的每一行都被拆分并输入到学生向量中,但我不知道如何提取该信息。

如上所述,每个元素都可以使用 operator[] 单独访问

或者,您可以使用迭代器来获取范围。学生。

 std::vector<Student>::iterator loop = students.begin();
 std::vector<Student>::iterator end  = students.end();

您可以通过取消引用循环访问一个元素,并通过递增循环移动到下一个学生。

 std::cout << loop->firstName;   // prints out student[0]
 ++loop;                         // Increment loop now it points at student 1
 std::cout << loop->firstName;   // prints out student[1]
 ++loop;                         // Increment loop now it points at student 2
 // etc

如果 loop == end 那么你已经超越了所有的学生。

如何将每个学生从学生向量中取出并放入自己的结构中,以便我可以将每个学生用作自己的结构?

学生已经在结构中的向量中。您可以像使用外部结构一样直接使用它们。但是如果你想把它们复制出来,你可以这样做:

Student   tmp = students[0]; // copies student 0 into tmp.

我希望能够输出:

使用 std::cout 将内容输出到标准输出。或者创建 std::ofstream 类型的对象以输出到文件:

std::cout << tmp.lastName  << " " 
          << tmp.firstName << " "
          << tmp.stdNumber << "\n";

std::ofstream  file("plop1.txt");
file      << tmp.lastName  << " " 
          << tmp.firstName << " "
          << tmp.stdNumber << "\n";

【讨论】:

  • 当我尝试使用std::cout 输出时,它给了我一个弹出窗口,上面写着"Debug Assertion Failed!" Expression: Vector iterator not dereferencable." 任何想法这是什么意思?我可以看到一个问题存在于一个不可解引用的循环中......
  • 您是否尝试取消引用传递到末尾的迭代器(如 end() 返回的迭代器所示)。
  • 我创建了一个 for 循环:for(loop;loop==end;++loop) 现在它显示为 vector iterators incompatible。你能解释一下吗?
  • 那里的小错误:确保它是 for(loop;loop!=end;++loop) 但不要在 cmets 中交谈,而是编辑您的问题。
  • 它编译得很好,但这是我得到的运行时错误。在fin.close() 之后
猜你喜欢
  • 2021-06-21
  • 1970-01-01
  • 2012-02-01
  • 2013-11-06
  • 2018-05-08
  • 2016-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多