1

I have 2 files in msg format. msg format is not important here.

car.msg

int speed;
int width;

cararr.msg

car mycar[];

I want to print all the information about all the cars that are present but I have no clue about the number of cars present(how big is the array) so I use the following technique to print the information.

so I do this:

cararr* ptr2car;
for(int i=0;mycar[i] != '\0'; i++){
      cout << ptr2car->mycar[i].speed <<endl;
      cout << ptr2car->mycar[i].width <<endl;
}

Despite this, I am receiving errors. I do not know what did I do wrong. I have no clue what approach should I use to get this output. please Help

Also why should I take a pointer to cararr, when I can just take an instance of cararr inst2car and do something like this:

 cararr inst2car;
    for(int i=0;mycar[i] != '\0'; i++){
          cout << inst2car.mycar[i].speed <<endl;
          cout << inst2car.mycar[i].width <<endl;
    }

thanks

4

1 回答 1

1

通常,您需要确切地知道数组末尾的内容。您需要某种标记值用作分隔符来指示数组的结尾。

c 字符串中使用的 '\0' 就是这种分隔符的一个示例。

您需要确保数组中的最后一个元素是这样的分隔符并在条件中检查它。

对于这样的通用问题,很难给你更具体的答案。

例如,如果您知道最后一个元素的速度为 -1,则可以使用:

for(int i=0;mycar[i].speed != -1; i++) {
于 2013-08-02T11:18:03.627 回答