0

I have a long long integer variable which holds data like 20101201

I need to split it up as 2010, 12 and 01.

Note: I need to do this in C program in my linux machine.

3
  • It's not clear whether you are using a long long integer (like you say) or a string (like the quotes and the tag suggests) to store that big number...
    – Dave
    Feb 1, 2011 at 10:22
  • @Dave - I'm getting long long integer value and need to store it as three different strings
    – Thi
    Feb 1, 2011 at 10:30
  • OK, I'll stick an answer in...
    – Dave
    Feb 1, 2011 at 11:26

4 Answers 4

5

You can divide by powers of 10 to get rid of numbers on the right:

(20101201/100/100)==2010

And the modulo of powers of 10 to get rid of numbers on the left:

(20101201%100)==01

And combine them to get the part in the middle:

(20101201/100)%100==12
1

This one should be ok with longs, and puts the answers into strings.

long long int lWholeThing = 20101201LL;
long long int lDate = lWholeThing % 100LL;
lWholeThing /= 100LL;
long long int lMonth = lWholeThing % 100LL;
lWholeThing /= 100LL;
long long int lYear = lWholeThing;

char sDate [3];
char sMonth [3];
char sYear [5];

sprintf (sDate, "%02d", (int) lDate);
sprintf (sMonth, "%02d", (int) lMonth);
sprintf (sYear, "%d", (int) lYear);
0

Try something like:

#include <stdlib.h> // for itoa() call -- built in to convert integer to string
#include <stdio.h>  // for printf() call

int main() {
    int num = 123;
    char buf[5];

    // convert 123 to string [buf]
    itoa(num, buf, 10);

    // print our string
    printf("%s\n", buf);

    return 0;
}

Then you can just complete your program by using index to split the numbers into different strings.

0
0

For the example you have given, you wanted to divide the number in to three sets: Pass your input as an argument to the executable.

int main( int argc, char **argv)
{

 long long int x;

 x=atoll(argv[1]);

 printf("\n %d", x%100);
 x=x/100;

 printf("\n %d", x%100);
 x=x/100;
 printf("\n %d", x);

}
1
  • Same problem..atoi can't handle long long int and the result has not been converted to string.
    – Terminal
    Feb 1, 2011 at 12:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.