Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn time char array into integers in C

I don't use C regularly so this is kind of tricky for me even though I'm sure it's a pretty simple task. I've been trying to research how to do this and I don't think I'm phrasing it correctly every time I search.

I need help figuring out how to turn the numbers in a char array into integers.

Basically, I'll have a char array like "1:09pm", "11:12AM", "11:12am", etc.

I'm trying to figure out how to separate the three things so I can figure out (1) the number of hours, (2) number of minutes, and (3) whether it's AM or PM (caps or not)

So far I think I have a way to get the first number:

char *time = arg[1]; // arg[1] is "1:09pm", etc
char *hours = strtok(time, ":");
int hours = atoi(hours);

From there, I'm not 100% sure what to do. Is there some sort of regular expression type parsing function that'll go from ":" to an alphabet character?

Thank you in advance!

like image 527
Laurence Avatar asked Feb 19 '14 00:02

Laurence


2 Answers

Just building on what you started...

char *time = arg[1]; // arg[1] is "1:09pm", etc
char *hours = strtok(time, ":ap");
char *mins = strtok(NULL, ":ap");
int ihours = atoi(hours);
int imins = atoi(mins);
if (strchr(time, 'a') == NULL) hours += 12;

The second call to strtok will find the next instance of any character in the token string you provide. So the second call will find either an 'a' or a 'p'. The atoi method will ignore alpha characters when it sees the a or p. The if statement is to scale your hours by am or pm.

Good luck!

like image 142
John Yost Avatar answered Oct 04 '22 17:10

John Yost


You can do it with a simple sscanf() call.

#include <stdio.h>

int main(){
    int hour, minute;   
    char c, time[] = {"1:23AM"};    

    // scan time for an int, a ':', another int and any char before another char.
    sscanf(time, "%d:%d%c%*c", &hour, &minute, &c);

    // to 24h format
    hour += (tolower(c) == 'p') ? 12 : 0;

    // just checking
    printf("%d h, %d min.\n", hour, minute);

}

sscanf() (and fscanf() too) is a very powerful tool, you can do all lot of parsing with it.

Take a look: http://www.cplusplus.com/reference/cstdio/scanf/

like image 31
Heeryu Avatar answered Oct 04 '22 16:10

Heeryu