Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Arduino.h>
- #include "esp_system.h"
- void reset_arr(int * const buf, int count)
- {
- for(int i = 0; i < count; i++)
- {
- buf[i] = -1;
- }
- }
- void print_arr(const char * name, const char * text, const int * buf, size_t buf_len)
- {
- Serial.printf("%s\n", name);
- Serial.printf(" LEN: %d", buf_len);
- Serial.printf(" TEXT: \"%s\"\n", text);
- for (int i = 0; i < buf_len; i++)
- {
- Serial.printf(" ITEM[%d]: %d\n", i, buf[i]);
- }
- }
- void setup() {
- Serial.begin(9600);
- const String str_val = "2021,5,9,15,10,0";
- int int_vals[8];
- const int int_vals_count = sizeof(int_vals) / sizeof(int_vals[0]);
- reset_arr(
- (int *)int_vals,
- int_vals_count);
- print_arr(
- "Before parsing",
- str_val.c_str(),
- (int *)int_vals,
- int_vals_count);
- //variant1
- reset_arr(
- (int *)int_vals,
- int_vals_count);
- int parsed_elems=sscanf(str_val.c_str(), "%d,%d,%d,%d,%d,%d",
- &int_vals[0], &int_vals[1], &int_vals[2],
- &int_vals[3], &int_vals[4], &int_vals[5]);
- print_arr(
- "Parsed variant 1 (sscanf)",
- str_val.c_str(),
- (int *)int_vals,
- parsed_elems);
- //variant2
- reset_arr(
- (int *)int_vals,
- int_vals_count);
- int i_v2 = 0;
- const char * const str_p_v2 = str_val.c_str();
- const char * cur_p_v2 = str_p_v2;
- do {
- int_vals[i_v2] = atoi(cur_p_v2);
- cur_p_v2 = strstr(cur_p_v2, ",");
- while(cur_p_v2 != NULL && cur_p_v2[0] == ',') {
- cur_p_v2 += sizeof(char);
- }
- i_v2++;
- } while (cur_p_v2 != NULL);
- int parsed_elems_v2 = i_v2;
- print_arr(
- "Parsed variant 2 (strstr+atoi)",
- str_p_v2,
- (int *)int_vals,
- parsed_elems_v2);
- //variant3
- reset_arr(
- (int *)int_vals,
- int_vals_count);
- int i_v3 = 0;
- const char * const str_p_v3 = str_val.c_str();
- char * cur_p_v3;
- char * rest_p_v3 = NULL;
- for (cur_p_v3 = strtok_r((char *)str_p_v3, ",", &rest_p_v3);
- cur_p_v3 != NULL;
- cur_p_v3 = strtok_r(NULL, ",", &rest_p_v3)) {
- int_vals[i_v3++] = atoi(cur_p_v3);
- }
- int parsed_elems_v3 = i_v3;
- print_arr(
- "Parsed variant 3 (strtok_r+atoi)",
- str_p_v3,
- (int *)int_vals,
- parsed_elems_v3);
- }
- void loop() {
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement