Question

I'm new to C and trying to split a character array (which I receive from a Serial Port in Ardunio). I looked up some tutorials and came up with this. Help me debug it please.

char action[10];
unsigned long duration;

void split(char input[20])
{
 char *param, *ptr;

 param = strtok_r(input, "#", &ptr);
 action = *param;                      // Need help with this line

 param = strtok_r(NULL, "!", &ptr);
 duration = (unsigned long) *param;    // Need help with this line
}

From what I understand, strtok_r returns a pointer to the character right after the delimiter(#). So if I wanted action[] to be a subset character array of input[] till the delimiter, what should I do?

Edit: Input is something like this: "left#1000!"

Was it helpful?

Solution

It looks like your first token is a string, and the second token is a long. You can use strncpy to copy param into action, and then strtoul to parse an unsigned long to duration.

param = strtok_r(input, "#!", &ptr);
strncpy(action, param, sizeof(action));
// Force zero termination
action[sizeof(action)-1] = '\0';

param = strtok_r(NULL, "#!", ptr);
duration = strtoul(param, &param, 10);

OTHER TIPS

You cannot initialize action = *param.

You need to use

memcpy(action, param, strlen(param))

and

duration = (unsigned long) atoi(param)

This snippet should work in plain C (comments added). You could use a C struct to collect values. Structs may be returned from functions like simple data types (as is shown). You could use that as a start for your own program.

Edit: Such programs don't need the strXYZ(..) functions (useful if you may have '\0'-bytes in your incoming data).

...

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

 typedef struct {
    char action[10];  unsigned long duration;
 } Result;


 Result split(char *input, char delim)
{
 Result result = {'\0', 0};                   // initialize result by zeros
 char *p = (char*)memchr(input, delim, sizeof(result.action)-1); 
 if(p != NULL) {                              // if delimiter found in input 
    memcpy(result.action, input, p-input);    // copy text till delimiter
    result.duration = strtoul(p+1, NULL, 10); // convert number after delimiter
 }
 return result;                               // return values
}

 int main(char argc, const char*argv[])
{
 char input[20] = "left#1000!";

 Result result = split(input, '#');
 printf("action: %s, duration %u\n", result.action, result.duration);

 return 0;
}

...

Regards

rbo

You should use strcpy() and necessary casting in order to assign strings(or char arrays) in C.

Visit http://en.cppreference.com/w/c/string/byte/strcpy

This function will care for membervise assignment between strings. To do it manually you must use loops and assign each array member seperately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top