将文本转换为数组

Converting text to array

我正在编写一个函数,将文本文件作为 class 对象读入数组,但编译器不允许我初始化 class 对象。它在初始化时给了我错误代码 "error: cannot convert 'std::array::value_type {aka BusinessContact}' to "BusinessContact*'。

这一行抛出异常contact[count ++] = con;

void ReadTransform(array<BusinessContact, maxsize> &contact, int&n)
{
  try
  {
    cout << "\nRead employees from file..." << endl;
    //open the file
    ifstream inFile("Contacts.txt", ios::in);
    if( !inFile )
      throw new string("Contacts.text not opened...");
    //read the file
    int count = 0;
    string firstName, Lastname, phoneNumber, emailAddress, company;
    BusinessContact *con;
    while (inFile>>firstName>> Lastname>> phoneNumber>> emailAddress>> company)
    {
      con = new BusinessContact(firstName, Lastname, phoneNumber, emailAddress, company);
      contact[count ++] = con;
      inFile.ignore();
    }
    for (BusinessContact *c : contact)
    {
      cout << c-> GetfirstName ()     << endl
        << c-> GetlastName()       << endl
        << c-> GetphoneNumber()    << endl
        << c-> GetemailAddress()   << endl
        << c-> Getcompany()        << endl;
    }

    inFile.close();
  }
  catch(string* msg)
  {
    cerr << "Exception: " + *msg << endl;
  }
}

您有一个 BusinessContact 对象数组 并且您尝试用 指针 填充它到 BusinessContact对象。不是一回事。

如果您遵循the rules of three, five or zero,您所要做的就是直接分配给数组中的条目。像

contact[count ++] = BusinessContact(firstName, Lastname, phoneNumber, emailAddress, company);;

或者,根据您的数据,您实际上可以直接从文件中读取到数组条目中:

while (inFile >> contact[count].firstName
              >> contact[count].Lastname
              >> contact[count].phoneNumber
              >> contact[count].emailAddress
              >> contact[count].company)
{
    ++count;
}

或者为什么不重载输入运算符,这样你就可以做到

while (inFile >> contact[count])
    ++count;

稍后当您遍历数组时使用常量引用,例如

for (BusinessContact const& c : contact) { ... }

con 的类型为 BusinessContact*。您正试图将 con 插入到 BusinessContact 数组中,contact.

做,

contact[count ++] = *con;