【发布时间】:2020-08-15 14:20:24
【问题描述】:
我在“.csv”文件中有一些数据表。我想将这些数据从该文件推送到向量。我尝试了 push_back。但它对我没有用。我实际上是一个初学者c++。有人可以帮我解决这个问题吗?
struct contacts {
string name;
string nickName;
string phoneNumber;
string carrier;
string address;
};
vector <contacts> proContactFile;
这是我从文件中读取值的部分(下)
void readContactDetails() {
ifstream ContactFile;
ContactFile.open("Contact.csv");
string readString;
if (ContactFile) {
while (!(ContactFile.eof())) {
getline(ContactFile, readString); // Read the column headers
for (int i = 0; i <= 10; i++) {
getline(ContactFile, limit[i].name, ','); // ',' is the separator
getline(ContactFile, limit[i].nickName, ',');
getline(ContactFile, limit[i].phoneNumber, ',');
getline(ContactFile, limit[i].carrier, ',');
getline(ContactFile, limit[i].address); // Read until the end of the line
}
proContactFile.push_back(ContactFile);
}
}
else {
cout << "Error"<< endl;//Show an error message if the file isn't opened
}
}
它总是显示错误信息 ->
no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=contacts, _Alloc=std::allocator<contacts>]" matches the argument list
谁能告诉我这是怎么回事?
【问题讨论】:
-
您的
vector是contacts类型的容器,但您是pushingifstream。 -
你有一个
vector <contacts>,所以你添加/push_back 的所有内容都必须是contacts类型,但你试图添加ContactFile这是一个ifstream,不是contacts. -
limit是什么类型? -
@drescherjm 在向量之后我放了一些类似下面的东西来设置一个限制。 ........ const int LIMIT = 10;联系人限制[LIMIT];
-
const int LIMIT = 10; contacts limit[LIMIT];您的代码正在尝试将 11 个项目读入这个大小为 10 的数组中。如果您有这个限制数组,那么您不需要proContactFile向量,因为它们的服务相同目的。