【问题标题】:How do I add different data types from text file into an array?如何将文本文件中的不同数据类型添加到数组中?
【发布时间】:2022-01-11 05:16:27
【问题描述】:

我正在尝试将文本文件中的这些数据类型添加到数组中,但出现超出范围的内存错误。文本文件如下所示:

1234,Chris Bobby,9/9/1999,123 Main Street,123-456-7890,5000.00

这是我的代码的样子:

void AddCustomersToArray(Customer *customers, fstream& customersFile) {
string line;
int i = 0;

string Number;
string FullName;
string DOB;
string Address;
string Telephone;
string Balance;

while (getline(customersFile, line)) {
    stringstream ss(line);

    getline(ss, Number, ',');
    customers[i].Number = stoi(Number);
    //cout << customers[i].Number << endl;

    getline(ss, FullName, ',');
    customers[i].FullName = FullName;
    //cout << customers[i].FullName << endl;

    getline(ss, DOB, ',');
    customers[i].DOB = DOB;
    //cout << customers[i].DOB << endl;

    getline(ss, Address, ',');
    customers[i].Address = Address;
    //cout << customers[i].Address << endl;

    getline(ss, Telephone, ',');
    customers[i].Telephone = Telephone;
    //cout << customers[i].Telephone << endl;

    getline(ss, Balance, ',');
    customers[i].Balance = stoi(Balance);
    //cout << customers[i].Balance << endl;

    i++;
}

【问题讨论】:

  • 你能显示调用代码吗?我们需要查看您为customers 传递的内容。
  • 你的数组大小是多少?该文件中有多少客户?
  • customers 是在全局范围内声明的客户结构数组,大小为 10。截至目前,该文件中有 2 个客户。这只是整个项目的一个 sn-p,因为后面还有一些函数可以让用户从文件中添加和删除客户。
  • 也许您只有两个客户的文件超过十行?

标签: c++ file-io


【解决方案1】:

也许您应该考虑使用矢量?然后你像这样动态增加所需的大小:

void AddCustomersToVector(std::vector<Customer>& customers, fstream& customersFile)
{
    //...
    while (getline(customerFile, line)) {
        Customer& newCustomer = customers.emplace_back();
        //...
        newCustomer.FullName = FullName;
        //...
    }
}

对向量的“emplace_back()”调用将在向量的末尾构造一个不带参数的“客户”,并交出这个“客户”的地址(作为参考)。 所以调用newCustomer.FullName = FullName会覆盖刚刚创建的“客户”的成员“全名”。

【讨论】:

  • 好的,是的,向量会更有意义,我只是不熟悉它们,因为我们没有在我的大学教过它们。我不理解“Customer&newCustomer=customers.emplace_back();”但是。
【解决方案2】:

我发现了这个问题。我在哪里:

getline(ss, Balance, ',');
customers[i].Balance = stoi(Balance);

我必须将其转换为双精度,而不是整数。因此,将其更改为修复它:

getline(ss, Balance, ',');
customers[i].Balance = stod(Balance);

【讨论】:

    猜你喜欢
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多