sscanf() and * character

hey there

I have a string :
(000000.000*kWh)

I want to use ssacnf() to seperate "000000.000" and "kWh" in different variables. I used code below but it didnt seperate well:

	char a[40];
	char b;
	strcpy(a,"(000000.000*kWh)");
	
/   sscanf(a,"(%s*%s)",&Modem.M_Data.Items[10].Value,&b,&Modem.M_Data.Items[10].Unit);

my question is how to define "*" in the string?

Do you have to use sscanf() ?

char input[] = {"000000.000*kWh"};

void setup()
{
  Serial.begin(115200);
  while (!Serial);
  char * p = strtok(input, "*");
  Serial.println(p);
  p = strtok(NULL, "*");
  Serial.println(p);
}

void loop()
{
}

yes I have to use sscanf() :confused:

  • has a special meaning in sscanf. ( and ) are not valid in the format specifier (to my knowledge); only variations on %s, %d etc and whitespace. See C library function - sscanf()

If you say that you have to use sscanf, this is more than likely homework :wink:

%s stops at the first whitespace character found. do you see any in your string?

not sure what you gain with sscanf... another version, somewhat similar to @UKHeliBob

char message[] = "000000.000*kWh";
void setup() {
  Serial.begin(115200);

  // 'destructive' approach but does not need more memory. pointers within the message buffer
  const char* value = NULL, *unit = NULL;
  char *starPtr = strchr(message, '*');
  if (starPtr) {
    value = message;
    unit = starPtr + 1;
    *starPtr = '\0';
    Serial.print(F("value = ")); Serial.println(value);
    Serial.print(F("unit = "));  Serial.println(unit);
  } else {
    Serial.println(F("Format Error"));
  }
}

void loop() {}

otherwise, if you know you'll always have 3 decimal digits, something like this

char message[] = "000000.000*kWh";
void setup() {
  Serial.begin(115200);

  long integral;
  char decimalString[5];
  char unitString[20];
  if (sscanf(message, "%ld.%3s*%s", &integral, decimalString, unitString) == 3) {
    Serial.print(F("value = ")); Serial.print(integral); Serial.write('.'); Serial.print(decimalString);
    Serial.print(F("\tunit = "));  Serial.println(unitString);
  } else {
    Serial.println(F("Format Error"));
  }
}

void loop() {}

What is the origin of the string that you are trying to parse ?

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.