简体   繁体   English

使用指针遍历数组的for循环无法正常工作

[英]For loop using pointers to traverse array not working properly

For my homework problem I must use pointers to traverse arrays. 对于我的作业问题,我必须使用指针来遍历数组。 When I try to store 3 "name" values into member variables of an array of an Object called RentalAgency , I find that it stores the value, but never increments. 当我尝试将3个“名称”值存储到名为RentalAgencyObject的数组的成员变量中时,我发现它存储该值,但从不增加。 Therefore the last value given is stored in the first index and the next two are empty. 因此,给定的最后一个值存储在第一个索引中,后两个为空。

RentalAgency *agencies_ptr = agencies;

for(int i = 0; i < 3;i++,++agencies_ptr){
    infile.get((agencies->name),MAX_SIZE,space);
}

Where agencies is an array of Objects agencies是一系列对象

If the input is Hertz, Alamo, and Budget, it should output Hertz, Alamo, and Budget. 如果输入为Hertz,Alamo和Budget,则应输出Hertz,Alamo和Budget。 The actual output is just Budget. 实际输出仅为预算。

Just write 写吧

for(int i = 0; i < 3; i++){
    infile.get( agencies_ptr[i].name, MAX_SIZE, space );
}

You are desreferencing agencies , not agencies_ptr (and the parenthesis are not needed): 您desreferencing agencies ,不agencies_ptr (并且不需要括号):

RentalAgency *agencies_ptr = agencies;

for(int i = 0; i < 3; ++i, ++agencies_ptr)
   infile.get(agencies_ptr->name, MAX_SIZE, space);

But a more idiomatic way of traversing a "range" is this ( it stands for iterator ): 但是遍历“范围”的一种更惯用的方式是这样的( it代表iterator ):

RentalAgency *agencies_it = agencies;
RentalAgency *agencies_end = agencies_it + 3;

for(; agencies_it != agencies_end; ++agencies_it)
   infile.get(agencies_it->name, MAX_SIZE, space);

It's cleaner, express intent better and is more familiar to see among experienced programmers. 它更干净,表达意图更好,并且在经验丰富的程序员中更熟悉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM