splitting strings and converting them to veriables

Status
Not open for further replies.

AdmiralCrunch

Well-known member
Hi

I want to save/load some project configuration-variables on/from my SD-Card (teensy 3.6).

reading and writing works fine, but now I struggle with what would be the best way (format) to store my config-vars in the file.
I was thinking about it like this:

Code:
myVar_1:23
myVar_2:35
myVar_3:65

how would i split the vars, so I can get a array like

myVars["myVar_1"] = 23;

or is this the wrong solution?
 
Hi

I want to save/load some project configuration-variables on/from my SD-Card (teensy 3.6).

reading and writing works fine, but now I struggle with what would be the best way (format) to store my config-vars in the file.
I was thinking about it like this:

Code:
myVar_1:23
myVar_2:35
myVar_3:65

how would i split the vars, so I can get a array like

myVars["myVar_1"] = 23;

or is this the wrong solution?

C++ does not support using strings as array indexes. There may be higher level libraries to do what you want. Without those libraries, you would need to write code to parse each line and store the value.
 
C++ does not support using strings as array indexes. There may be higher level libraries to do what you want. Without those libraries, you would need to write code to parse each line and store the value.

ok , thanks.

but how would I split a string like

varname:value

so I only get the value? I know from js (split()) or php (substr()).. but hw is that in c++ ? oO
 
ok , thanks.

but how would I split a string like

varname:value

so I only get the value? I know from js (split()) or php (substr()).. but hw is that in c++ ? oO

If you read the value into a char [] array, and you won't need the array's value after the processing, you can use the C string library:

Code:
#include <string.h>
#include <ctype.h>

void
set_values (char buffer[])
{
  char *p = strchr (buffer, ':');
  if (p && isdigit (*p+1)) {
    long value = strtol (p+1, (char **)0, 0);
    // Found ':', set it to null, so we can do strcmp's.  Strcmp returns 0 if the strings are equal
    *p = '\0';
    if (strcmp (buffer, "command1") == 0) {
      command1 = value;

    } else if (strcmp (buffer, "command2") == 0) {
      command2 = value;

    } else {
      Serial.print ("Unknown command ");
      Serial.println (buffer);
    }

  } else {
    Serial.print ("Bad input ");
    Serial.println (buffer);
  }

  return;
}
 
Status
Not open for further replies.
Back
Top