gpt4 book ai didi

c++ - 将文本转换为数组

转载 作者:行者123 更新时间:2023-11-27 22:54:50 25 4
gpt4 key购买 nike

我正在编写一个函数,将文本文件作为类对象读入数组,但编译器不允许我初始化类对象。它给了我错误代码,“错误:无法在初始化时将'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;
}
}

最佳答案

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

关于c++ - 将文本转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34252934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com