c++ - 将文件读入 vector ,我的输入函数有什么问题?

标签 c++ class vector

我有一项任务是为类(class)项目创建记录管理系统。添加记录时,我想首先将当前记录文件的内容读入 vector ,然后对文件执行添加,最后输出回记录文件。但是,我很难思考如何构建它。我目前正在使用动态数组来存储数据,但是当我尝试将其放入 vector 时,它不会让我这样做,因为它是一个指针。我觉得我完全错误地处理了这个问题,需要一些帮助。这是我的输入函数:

 void student::input(istream& inF, student* stud, vector<student>& vect, int size)
{
    //local variables
    string first, middle, last, addressNum, addressStreet, 
        phone, gender, email, emContactFirst, emContactLast;
    int ID, age;
    string ph, emPhone;
    while (inF)
    {
        for (int index = 0; index < size; index++){
            inF >> first >> last >> middle;
            stud->setName(first, last, middle);
            inF >> ID;
            stud->setId(ID);
            inF >> age;
            stud->setAge(age);
            inF >> phone;
            stud->setPhone(phone);
            inF >> addressNum >> addressStreet;
            stud->setAddress(addressNum, addressStreet);
            inF >> gender;
            stud->setGender(gender);
            inF >> email;
            stud->setEmail(email);
            inF >> emPhone;
            stud->setEmPhone(emPhone);
            inF >> emContactFirst >> emContactLast;
            stud->setEmContact(emContactFirst, emContactLast);
            inF >> stud->gpa >> stud->hobbies >> stud->major
                >> stud->probation;
            if (inF.eof())
                break;
            else
            stud++;
            vect.push_back(stud);
        }
    }
}

最佳答案

我看到的问题:

  1. 您正在使用 while (inF) 来打破循环。参见 Why is iostream::eof inside a loop condition considered wrong? .

  2. 您正在使用一个指针 stud 读取所有值并在 vect 中多次存储同一个指针。首先,编译器应该产生一个错误。您不能添加指向对象 vector 的指针。

    不清楚为什么函数需要 stud 作为参数。您可以在函数中轻松使用本地对象。像这样:

    for (int index = 0; index < size; index++){
       student stud;
       if ( !(inF >> first >> last >> middle) )
       {
          // Deal with error.
       }
       stud.setName(first, last, middle);
    
       ...
    }
    
  3. 最好检查对 inF >> ... 的调用是否成功分配了任何内容,而不是假设它成功了。而不是:

    inF >> first >> last >> middle;
    

    使用

    if ( !(inF >> first >> last >> middle) )
    {
        // Deal with error.
    }
    

    我建议更改所有此类调用。

关于c++ - 将文件读入 vector ,我的输入函数有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33529343/

相关文章:

c++ - 如何操作字符数组

c++ - CharConverter 未知错误

c++ - 链接ibus(libibus),cmake中的glib

algorithm - 关于类的一般编程问题

c++ - 为什么我们可以push_back仅用range定义的子 vector ?

c++ - 搜索链表和数组时有什么区别?

Android: View 在调用setContentView R.layout之前显示

c++ - 我可以在类声明中声明一个数组,稍后该数组将填充该类的元素吗?

string - 在 Rust hashmap 中分配/实例化字符串/向量的向量?

vector - 高效的线条平滑和/或简化