Go Down

Topic: Read from one character in string to another (Read 432 times) previous topic - next topic

AKSoapy29

Hello everyone,

I have a string of data in one of my Arduino programs, and I need to break it apart. The string will hold things like:
M1:1023;
M2:25;

or other things like that. I am wondering how I can great only things that are between : and ; so for M1, I would get 1023 saved to a variable. For M2, 25 would be saved to that variable.

----

I was watching a video on Youtube about I2C, and Jeremy did, what he used things like data_length(); and data.substring(); except that was in Processing.
Andrew K.

guix

#1
Mar 16, 2013, 01:27 am Last Edit: Mar 16, 2013, 01:33 am by guix Reason: 1
Hello :)

Using sscanf is the easiest solution I think.

Code: [Select]

int var;
char str[] = "M1:1023;";
sscanf( str, "M1:%d;", &var );
// var is now = 1023


Edit: sorry I meant, sscanf not sprintf ;)

majenko


Hello :)

Using sprintf is the easiest solution I think.

Code: [Select]

int var;
chat str[] = "M1:1023;";
sprintf( str, "M1:%d;", &var );
// var is now = 1023


Not with sprintf you won't.  That will put "M1:308" into the variable str (where 308 is the address of the variable "var").

I think you meant sscanf().

guix

Of course... I'm a little tired :smiley-zipper:

There is another solution that is, using atoi, like this:

Code: [Select]

char str[] = "M1:1023;";
int var = atoi( &str[3] );
//var now = 1023

AKSoapy29

Awesome! Thank you. I don't know anything about atoi, but wouldn't that make var = 1023; instead of 1023?
Andrew K.

PaulS

Quote
but wouldn't that make var = 1023; instead of 1023?

int var = 27;
What is the value in var? 27 or 27;?

If you said 27;, you were wrong.

AKSoapy29


Quote
but wouldn't that make var = 1023; instead of 1023?

int var = 27;
What is the value in var? 27 or 27;?

If you said 27;, you were wrong.


Ok, I was just curious because I have never used atoi before.
Andrew K.

PaulS

Quote
because I have never used atoi before.
   

Or googled it either, apparently.

Go Up