编辑:好的,在下面帖子的帮助下,我编译了它。我将读取文件到数组的行更改为:
input->read((char*)( &(zip[i].postalCode) ), sizeof(int ));
input->read((char*)( &junk ), sizeof(int ));
input->read((char*)( &(zip[i].longitude) ), sizeof(double ));
input->read((char*)( &(zip[i].latitude) ), sizeof(double ));
cout << "Currently at position" << input->tellg() << endl;
现在我让它运行循环的第一次迭代,但随后出现段错误。
Currently at position24
Segmentation fault (core dumped)
以下为原帖:
我又来了。 A 有一个结构和几个函数:
struct zipType{
int postalCode;
double longitude;
double latitude;
};
void zipToCout(zipType zip){
cout << "Postal Code = " << zip.postalCode << "\tLongitude = " << zip.longitude << "\t\tLatitude = " << zip.latitude << endl;
}
void binRead(zipType *zip[], fstream *input){
int junk;
int count;
int end;
input->seekg(0,ios::end);
end=input->tellg();
count=input->tellg()/24;
input->seekg(0);
while(input->tellg()!=end){
for(int i=0;i<count;i++){
input->read((char*)( &zip[i]->postalCode ), sizeof(int ));
input->read((char*)( &junk ), sizeof(int ));
input->read((char*)( &zip[i]->longitude ), sizeof(double ));
input->read((char*)( &zip[i]->latitude ), sizeof(double ));
cout << "Currently at position" << input->tellg() << endl;
//zipToCout(*zip);
}
}
}
现在,我主要创建了一个 zipType[n]
,其中 n 是 .bin 文件中 zipType 的数量。然后我调用了 binRead(&testZipType[n],&testFile);
。这给了我一些你可以想象的错误。我收到一些与此类似的错误:
zipType.cpp:22:32: error: base operand of ‘->’ has non-pointer type ‘zipType’
input->read((char*)( &zip[i]->postalCode ), sizeof(int ));
我需要做的是遍历文件并将结构的每个部分存储在数组的相应部分中。我试图做尽可能少的改变来完成这项工作。我知道你们中的一些人可以 *<@LD(#) 通往荣耀的道路,但我还没有到那里,希望能够阅读我的代码。另外,我需要对数组进行 qsort 以按升序对其进行排序(我还没有尝试过这个,如果你能帮助我完成第一部分,我会自己试一试。)谢谢你的帮助!希望很快我就能回馈这里!
最佳答案
我假设 zip 是一个动态数组。是吗?
所以当你声明你的数组时,你正在做一些事情:
zipType* z = new zipType [10];
您的函数 binRead 应该这样声明:
void binRead(zipType *zip, fstream *input){
当你调用binRead时,你不想得到指针的地址
binRead(&z,input);
相反,你想传递你的指针,z:
binRead(z,input);
在 binRead 内部确保像这样引用 zip:
zip[i].postalCode
因为您已经传递了一个指针,所以您在 binRead 中所做的所有更改都将对 zip 指向的内存进行。
这是一个演示我在说什么的小程序:
#include <iostream>
struct zipType{
int postalCode;
double longitude;
double latitude;
};
void blah(zipType *zip){
for (int i=0;i<10;i++){
std::cout << zip[i].postalCode << std::endl;
}
zip[0].postalCode = 60626;
}
int main(int argc, const char * argv[])
{
zipType* z = new zipType [10];
for(int i=0;i<10;i++){
z[i].longitude = i * 10;
z[i].latitude = i * 5;
z[i].postalCode = i * 6;
}
blah(z);
std::cout << z[0].postalCode;
delete [] z;
}
关于c++ - 将文件读入结构数组,然后排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19992503/