I want to create a function to take a string like this "2014-02-13T06:20:00"
and to convert to a long long int
like 20140213062000
.
Has anyone a idea how this can be done?
I want to create a function to take a string like this "2014-02-13T06:20:00"
and to convert to a long long int
like 20140213062000
.
Has anyone a idea how this can be done?
Here is an algorithm, you will just write the code:
long long
variable n
and initialize it to 0
.c
in the string:
c
is a digit, ie greater or equal to '0'
and less or equal to '9'
:n
by 10
and add the value represented by c
, store the result in n
.n
should have the expected value.This would convert positive values. If the string has an initial -
indicating a negative number, you would test that and negate the number at the end. Note also that overflowing the range of long long int
has undefined behavior with this approach.
Your attempt in the comment needs some improvements:
long long string_To_long(const char sl[]) {
long long int n = 0;
for (int i = 0; sl[i] != '\0'; i++) {
char c = sl[i];
if (c >= '0' && c <= '9')
n = n * 10 + (c - '0');
}
return n;
}