views:

99

answers:

2

I need to append a number at the end of the word flare depending on how many I have. That part works great. My problem is when I go to print it to the screen. I would like the program to output the value of what (Camera::Table[Id]->sensor->flare1) sensor is pointing at, in this case, flare one. If the program were to continue it would output the value pointing at flare2, flare3, flare4,... until the limit is reached.
What I get as the output is the following:

lens_pos1=¨Camera::Table[Id]->sensor->flare1¨ 
lens_pos2=¨Camera::Table[Id]->sensor->flare2¨ .......  

How can I output the value of flare1 instead of pasting the string?

What I want is the following:

lens_pos1=¨10.3¨ lens_pos2=¨12.4¨..... 

Where the values 10.3, 12.4 would be those of flare1 and flare2 respectively taken from a seperate C file.

for(int i = 1; i <= nbflares; i++)  
{  
    char integer_string[32];  
    sprintf(integer_string, "%d", i);  
    char flare[100] = "Camera::Table[Id]->sensor->flare";

    strcat(flare,integer_string);

    fprintf(yyout, "lens_pos%d=\"%s\" ",i,flare);
}
+3  A: 

You can't access a variable like that in C/C++. You have to redesign the "sensor" structure to contain an array instead of individual flares, and access the array by index: Camera::Table[Id]->sensor->flare[1], Camera::Table[Id]->sensor->flare[2], etc.

@Merlyn Morgan-Graham: the question shows sensor->flare1, sensor->flare2, which supports this answer's relevance.
Tony
+1  A: 

That can't be done in C++. Some interpreted languages might allow such things because the text of the source code still exists while the program is running. But in C++, when you compile a program all the names of classes and variables and such are essentially lost. When it gets to the point of a running executable, the actual machine instructions are just working with offsets and memory addresses.

So you need re-design how the data is stored.

Is there a way to access them without the use of arrays?

Technically, yes. But only by using a more complicated scheme that would involve a more complicated data structure (such as a linked list or map).

Why would you want to avoid arrays anyway? Right now you have a series of variables of the same type that you want to distinguish by the number are the end of their names. And an array is a series of variables of the same type that are distinguished by their index in the array. It's pretty much a perfect match.

For example, if you had a flares array, then you could simply do something like:

for(int i = 0; i < nbflares; i++)  
{  
    fprintf(yyout, "lens_pos%d=\"%f\" ", i, Camera::Table[Id]->sensor->flares[i]);
}
TheUndeadFish
Thank you! I figured that there might be an easier way since I am just at the very beginning of my programming experiences. If arrays are the simplest way to go then that is the route I shall take. I was just hoping that there would be a line that I can add to the code to output it differently but I guess not.
gianx