filimonic

Arduino number seq parsing

May 10th, 2021
523
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <Arduino.h>
  2. #include "esp_system.h"
  3.  
  4. void reset_arr(int * const buf, int count)
  5. {
  6.   for(int i = 0; i < count; i++)
  7.   {
  8.     buf[i] = -1;
  9.   }
  10. }
  11.  
  12. void print_arr(const char * name, const char * text, const int * buf, size_t buf_len)
  13. {
  14.   Serial.printf("%s\n", name);
  15.   Serial.printf("    LEN:  %d", buf_len);
  16.   Serial.printf("    TEXT: \"%s\"\n", text);
  17.   for (int i = 0; i < buf_len; i++)
  18.   {
  19.     Serial.printf("    ITEM[%d]: %d\n", i, buf[i]);
  20.   }
  21. }
  22.  
  23. void setup() {
  24.   Serial.begin(9600);
  25.   const String str_val = "2021,5,9,15,10,0";
  26.   int int_vals[8];
  27.   const int int_vals_count = sizeof(int_vals) / sizeof(int_vals[0]);
  28.   reset_arr(
  29.       (int *)int_vals,
  30.       int_vals_count);
  31.   print_arr(
  32.     "Before parsing",
  33.     str_val.c_str(),
  34.     (int *)int_vals,
  35.     int_vals_count);
  36.  
  37.   //variant1
  38.   reset_arr(
  39.     (int *)int_vals,
  40.     int_vals_count);
  41.   int parsed_elems=sscanf(str_val.c_str(), "%d,%d,%d,%d,%d,%d",
  42.     &int_vals[0], &int_vals[1], &int_vals[2],
  43.     &int_vals[3], &int_vals[4], &int_vals[5]);
  44.   print_arr(
  45.     "Parsed variant 1 (sscanf)",
  46.     str_val.c_str(),
  47.     (int *)int_vals,
  48.     parsed_elems);
  49.  
  50.   //variant2
  51.   reset_arr(
  52.     (int *)int_vals,
  53.     int_vals_count);
  54.  
  55.   int i_v2 = 0;
  56.   const char * const str_p_v2 = str_val.c_str();
  57.   const char * cur_p_v2 = str_p_v2;
  58.   do {
  59.     int_vals[i_v2] = atoi(cur_p_v2);
  60.     cur_p_v2 = strstr(cur_p_v2, ",");
  61.     while(cur_p_v2 != NULL && cur_p_v2[0] == ',') {
  62.       cur_p_v2 += sizeof(char);
  63.     }
  64.     i_v2++;
  65.   } while (cur_p_v2 != NULL);
  66.   int parsed_elems_v2 = i_v2;
  67.   print_arr(
  68.     "Parsed variant 2 (strstr+atoi)",
  69.     str_p_v2,
  70.     (int *)int_vals,
  71.     parsed_elems_v2);
  72.  
  73.  
  74.   //variant3
  75.   reset_arr(
  76.     (int *)int_vals,
  77.     int_vals_count);
  78.  
  79.   int i_v3 = 0;
  80.   const char * const str_p_v3 = str_val.c_str();
  81.   char * cur_p_v3;
  82.   char * rest_p_v3 = NULL;
  83.  
  84.   for (cur_p_v3 = strtok_r((char *)str_p_v3, ",", &rest_p_v3);
  85.     cur_p_v3 != NULL;
  86.     cur_p_v3 = strtok_r(NULL, ",", &rest_p_v3)) {  
  87.       int_vals[i_v3++] = atoi(cur_p_v3);
  88.   }
  89.  
  90.   int parsed_elems_v3 = i_v3;
  91.   print_arr(
  92.     "Parsed variant 3 (strtok_r+atoi)",
  93.     str_p_v3,
  94.     (int *)int_vals,
  95.     parsed_elems_v3);
  96. }
  97.  
  98. void loop() {
  99.  
  100. }
RAW Paste Data