我正在处理一个问题,涉及从文件中读取信息,将信息保存到结构和类的数组中,然后显示信息。为了简洁起见,我省略了一些函数定义。我的代码适用范围如下:
void getInputFile (RentalAgency *ptr) {
int a=0, b=0, c=0;
int tempYear;
float tempPrice;
char tempMake[264], tempModel[264];
bool tempAvailable;
ifstream inputStream;
int *zipCodePtr=(*ptr).zipcode; //create pointer to struct zipcodes
RentalCar *inventoryPtr=(*ptr).inventory; //create pointer to an array of classes
while (a<3) {
输出应该是这样的:
Hertz 93619
2014 Toyota Tacoma, $115.12 per day, Available: 1
2012 Honda CRV, $85.1 per day, Available: 0
2015 Ford Fusion, $90.89 per day, Available: 0
2013 GMC Yukon, $110.43 per day, Available: 0
2009 Dodge Neon, $45.25 per day, Available: 1
Alamo 89502
2011 Toyota // more information is posted similar to above
相反,我的 ptr 变量似乎有错误,因为它显示:
Hertz 93619
2014 Toyota Tacoma, $115.12 per day, Available: 1
2012 Honda CRV, $85.1 per day, Available: 0
2015 Ford Fusion, $90.89 per day, Available: 0
2013 GMC Yukon, $110.43 per day, Available: 0
2009 Dodge Neon, $45.25 per day, Available: 1
Alamo
89502 //It stops printing here
在尝试解决此问题时,我注意到在递增 ptr 和显示机构名称时,它首先打印 Hertz,然后是 Alamo,然后是 89502(与下一个名称相反),然后是乱码。显然,从第二和第三机构的输入文件(仅供引用,类似于显示格式)中保存信息存在问题。非常感谢任何帮助。 C 与库存数组的大小有关,b 与邮政编码数组的大小有关,a 与我要保存和显示的 3 个机构有关。
最佳答案
在两个例程中,每次通过外循环都需要重置b
和c
。发生的事情是(在输入和输出例程中)b
和 c
在第一次通过外部 (a
) 循环。
您可以通过将b
和c
的初始化移到while 循环中来解决这个问题。
while(a < 3)
{
int b = 0, c = 0;
// ... rest of code ...
}
关于C++——指向结构数组的指针包含指向不起作用的类数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54663248/