Morta1
Morta1

Reputation: 619

Spliting string to an array in C

int main() 
{
    int longNum = 12345, tempNum[5], i;
    for (i = 0; i <= 5; i++)
    {
        tempNum[i] = longNum[i] ; // not valid, how do i make this work?
    }
    printf("%d\n", tempNum);
    return 0;
}

Im trying to go through all the digits of longNum and push them into tempNum[].

Upvotes: 0

Views: 70

Answers (4)

Prophet Daniel
Prophet Daniel

Reputation: 327

#include <stdio.h>
int main()
{
    int longNum = 12345, tempNum[5], i;
    for (i = 1; i <= 5; i++)
    {
        tempNum[5-i] = longNum % 10;
        longNum = longNum/10;
    }
    printf("%d%d%d%d%d\n", tempNum[0], tempNum[1], tempNum[2], tempNum[3], tempNum[4]);
    return 0;
}

Upvotes: 0

BobRun
BobRun

Reputation: 754

You could try this:

int main(  )
{
  int longNum = 12345, tempNum[5], i;
  char numstr[99];

  itoa( longNum, numstr, 10 );

  for ( i = 0; i < 5; i++ )
{
    tempNum[i]=numstr[i] - '0';
    printf( "\n%d", tempNum[i] );
}

  return 0;
}

Upvotes: 0

tdao
tdao

Reputation: 17678

For a dynamic length:

#include <stdio.h>
#include <stdlib.h>

int main() 
{
    long long longNum = 1234512345;  // can be any size within `long long` limit.
    int tempNum[5], i;

    int num_digits = 0;
    long temp = longNum;
    while( temp > 0 )
    {
        temp /= 10;
        num_digits++;
    }
    printf( "num_digits = %d\n", num_digits );

    // Allocate dynamic array.
    int *pos = malloc( num_digits * sizeof( int ) );

    for( i = num_digits - 1; i >= 0; i-- )
    {
        pos[i] = longNum % 10;
        longNum /= 10;
    }

    for( i = 0; i < num_digits; i++ )
    {
        printf("%d\n", pos[i]);
    }

    return 0;
}

Upvotes: 0

tdao
tdao

Reputation: 17678

You may try the modulo operator:

int main() 
{
    int longNum = 12345, tempNum[5], i;

    for (i = 4; i >= 0; i--)
    {
        tempNum[i] = longNum % 10;
        longNum /= 10;
    }

    for( i = 0; i < 5; i++ )
    {
        printf("%d\n", tempNum[i]);
    }
    return 0;
}

Upvotes: 1

Related Questions