C++ Question Reading a scenario line with 'n' variables

Hlynkacg

Aspiring rocket scientist
Addon Developer
Tutorial Publisher
Donator
Joined
Dec 27, 2010
Messages
1,870
Reaction score
3
Points
0
Location
San Diego
As the title suggests, I'd like some help with parsing scenario files.

I know how to use sscanf() to read a known # of variables off a line, but how would I go about adapting it to an unknown number of variables?

The context is as follows. I currently have a std::map container that is used to store all of my spacecraft's panel elements using their active area ids. The save function generates a string of number pairs that contain the id and state of each panel element currently declared. Because the string gets longer or shorter depending on the number of elements declared I have to keep going back and modifying ParseScenarioLine() function each time an element is added or commented out which is both annoying and time consuming.

I I'd like to be able to write the "ParseScenarioLine()" function once rather having to modify it each time a panel element is added or removed but I'm not sure how.
 
Last edited:

GLS

Well-known member
Orbiter Contributor
Addon Developer
Joined
Mar 22, 2008
Messages
5,937
Reaction score
2,949
Points
188
Website
github.com
Checkout the strtok function.
 

Hlynkacg

Aspiring rocket scientist
Addon Developer
Tutorial Publisher
Donator
Joined
Dec 27, 2010
Messages
1,870
Reaction score
3
Points
0
Location
San Diego
Ok that looks promising, If I'm understanding it correctly, the following code will populate the "input" array with the integers found.

Code:
int tmp = 0;
int count = 0;
int input[1024];

char * token;
token = strtok(line, " ,.-");
while (token != NULL)
{
   if (sscanf(token, "%d", &tmp) > 0)
   {
      input[count++] = tmp;
   }

   token = strtok(NULL, " ,.-");
}

...and from there step through the array using a standard "for" loop. Have I missed anything?
 
Last edited:

GLS

Well-known member
Orbiter Contributor
Addon Developer
Joined
Mar 22, 2008
Messages
5,937
Reaction score
2,949
Points
188
Website
github.com
Ok that looks promising, If I'm understanding it correctly, the following code will populate the "input" array with the integers found.

Code:
int tmp = 0;
int count = 0;
int input[1024];

char * token;
token = strtok(line, " ,.-");
while (token != NULL)
{
   if (sscanf(token, "%d", &tmp) > 0)
   {
      input[count++] = tmp;
   }

   token = strtok(NULL, " ,.-");
}

...and from there step through the array using a standard "for" loop. Have I missed anything?

That should work. :cheers:
 

Hlynkacg

Aspiring rocket scientist
Addon Developer
Tutorial Publisher
Donator
Joined
Dec 27, 2010
Messages
1,870
Reaction score
3
Points
0
Location
San Diego
Got it up and running, thank you again :cheers:
 
Top