将文本转换为数组

时间:2015-12-13 15:48:47

标签: c++ pointers text ifstream

我正在编写一个函数来将文本文件作为类对象读入数组,但是编译器不允许我初始化类对象。它给了我错误代码,"错误:无法转换' std :: array :: value_type {aka BusinessContact}'到" 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;
  }
}

2 个答案:

答案 0 :(得分:2)

您有一组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) { ... }

答案 1 :(得分:2)

con的类型为BusinessContact *。您想将con插入到BusinessContact数组中,联系。

DO,

$( "input[name*='PAN_purchaser']" ).val( "the value you want" );
$( "input[name*='PAN_seller']" ).val( "the value you want" );
$( "input[name*='PAN_seller_confirm']" ).val( "the value you want" );