MICRO
MICRO

Reputation: 251

Extract int values from string

I have a incoming string like this :- *DDMMYYHHMMSS# DD Stands for Date, MM stands for month, YY stands for year, HH stands for Hour...

Example *021216213940# (Date : 2nd December, 2016 Time : 21:29:40)

How can I extract values from above given string and copy to int data type.

int Date,Month,Year,Hours,Minutes,Seconds;

Upvotes: 1

Views: 457

Answers (2)

freestyle
freestyle

Reputation: 3790

You can use scanf family functions, like this:

char *incoming = "*021216213940#";
int day, month, year, hours, minutes, seconds;
if (6 != sscanf(incoming, "*%2d%2d%2d%2d%2d%2d#", &day, &month, &year, &hours, &minutes, &seconds))
{
    ... /* handle invalid input here */
}

Upvotes: 2

Ziezi
Ziezi

Reputation: 6467

To convert the content of your string you need to convert to (a two digit) decimal, which is a ten-based positional system.

For example to extract the first two digits you use subscript operator[], i.e. str[1] and str[2], to convert from char to int you subtract '0' character utilising ASCII character ordering and finally to ensure correct position of the digits you multiply by 10:

int DD = (str[1] - '0') * 10 + str[2] - '0';

Upvotes: 1

Related Questions