Reputation: 195
I have data in my .txt file containing different time ins and time outs of employees. For example, 10:20
but I initially designed the structure to have their data types to be of char arrays or string. Since I'll be using the time values in another function, I have to use the atoi() function to convert them into integer values. Problem is, there is a colon :
in each of the time values. Would it be possible to convert the string 10:20
to an integer using atoi() so that I can it in my future functions? Does the use of atoi() allow some splitting or some sort so that I can convert my time value from string to int?
I tried
char time[10] = "10:20";
int val;
printf("string val = %s, int value = %d", time, atoi(time));
But my output is only
string val = 10:20, int value = 10
so only the string before the :
is read and converted to string. I would want that after converting, I would stil have 10:20 as the result but in integer because I am going to use relational operators with it.
Upvotes: 1
Views: 174
Reputation: 29985
You can also use sscanf
:
#include <stdio.h>
int main() {
char const* time = "10:20";
int h, m;
if (sscanf(time, "%d:%d", &h, &m) != 2)
return 1;
printf("string val = %s, int value = %d\n", time, h * 100 + m);
}
Upvotes: 0
Reputation: 212404
It's not clear what you actually want, but maybe something like:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
char *time = argc > 1 ? argv[1] : "10:20";
int d;
char *e;
d = strtol(time, &e, 10);
if( *e == ':' ){
d *= 100;
d += strtol(e + 1, &e, 10);
}
if( *e != '\0' ){
fprintf(stderr, "invalid input\n");
return 1;
}
printf("string val = %s, int value = %d\n", time, d);
return 0;
}
This will produce d = 1020
for the string "10:20". It's not at all clear to me what integer you want to produce, but that seems to be what you're looking for.
Upvotes: 1