Go Down

Topic: Converting String "01:02:03" to int array[2] (Read 855 times) previous topic - next topic

RjSowden

So I've got a GPS unit that send the time to my arduino in form XX:XX:XX and I want to take the integers from this and place them in an integer array so that int[2] is the seconds, int[1] is the minutes and int[0] is the seconds. I've tried various combinations of String.charAt, String.substring and atoi, and all I've gotten is nowhere due to an immense amount of errors.

Please help!

Thank you so much!



An example of what I want doing, in case I've explained it badly up there:
'String time = "01:02:03"' going into 'int currentTime[2] = {1,2,3}'

majenko

If you store the string in a char * instead of a String object, then you can use sscanf:

Code: [Select]

char *time = "01:02:03";
int tdata[3];

sscanf(time,"%d:%d:%d",&tdata[0],&tdata[1],&tdata[2]);

Krodal

#2
Jul 13, 2012, 06:00 pm Last Edit: Jul 13, 2012, 06:04 pm by Krodal Reason: 1
The size of the int arry is 3.
To use index 0,1,2 you need: int CurrentTime[3];

Since the string is fixed, I would use old-style character handling, and not a string class.

Code: [Select]

// The time has format "01:02:03", hh:mm:ss
char time[16];

// currentTime has format [0] : seconds, [1] :  minutes, [2] : hours
int currentTime[3];

currentTime[0] = (10 * (time[6] - '0')) + (time[7] - '0');
currentTime[1] = (10 * (time[3] - '0')) + (time[4] - '0');
currentTime[2] = (10 * (time[0] - '0')) + (time[1] - '0');


or using atoi
atoi will stop if a non-digit is found
Code: [Select]

...
char *p = time;         // not sure, not tested

currentTime[0] = atoi (p+6);
currentTime[1] = atoi (p+3);
currentTime[2] = atoi (p+0);


While I was typing this message, majenko gave an example with sscanf. That's also a good solution. There must be more solutions, so just use the one you understand best.

RjSowden

sscanf didn't seem to work particularly well for me (RE, Not at all. Not sure If I was using it right TBH though ;) ), so in the end I went with the last suggestion, being as I understood it. Works good enough, Thanks so much for your help guys!

jraskell


sscanf didn't seem to work particularly well for me (RE, Not at all. Not sure If I was using it right TBH though ;) )


Really?  Can you show the code that wasn't working?  sscanf should work fine, and could even prove to be more robust as it won't really break with a variety of input.  ie, Majenko's snippet would work fine with the following strings as well:

"1:322:66"
or
"0:4:6"

If your string format is strictly defined, then it's not really a problem either way, I'm just curious why sscanf didn't work for you.

Go Up