[英]How do I add different data types from text file into an array?
我正在尝试将这些数据类型从文本文件添加到数组中,但出现超出范围 memory 错误。 文本文件如下所示:
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++;
}
也许您应该考虑使用向量? 然后你像这样动态增加所需的大小:
void AddCustomersToVector(std::vector<Customer>& customers, fstream& customersFile)
{
//...
while (getline(customerFile, line)) {
Customer& newCustomer = customers.emplace_back();
//...
newCustomer.FullName = FullName;
//...
}
}
我弄清楚了这个问题。 我在哪里:
getline(ss, Balance, ',');
customers[i].Balance = stoi(Balance);
我必须将其转换为双精度,而不是 integer。 因此,将其更改为此修复了它:
getline(ss, Balance, ',');
customers[i].Balance = stod(Balance);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.