-3

So I tried to get a number(int) from the user and move the number from the integer to the empty string, and than i need to print it like a string. help?

   #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#define  CHAR_LENGTH 100
int main()
{
    int num =0,units=0 ,length=0,counter =0,i=0 ;
    char charNumber[CHAR_LENGTH]={0};
    printf("enter some number(positive or negative)\n");
    scanf("%d",&num);
    while (num != 0)
    {
        units =0;
        units = num %10;
        num = num / 10;
        charNumber[i]= (char)units;
        counter++;
        i++;
    }
    printf("%s",charNumber);
    return 0;
}
blackFish
  • 85
  • 1
  • 1
  • 8

2 Answers2

2

Do you need to write an algorithm yourself? If not, use itoa function of C standard library (although it's not so standard, but some libraries include it).

You can also use sprintf like this:

int value = 2016;
char my_string[64];

snprintf(my_string, 64, "%d", value);

Check out these links as well:

Community
  • 1
  • 1
ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

Three problems:

(1) Negative numbers. if (num < 0) { printf("-"); num = -num; }
(yes, I ignored the obvious corner case)

(2) You print the digits in the backwards order.

(3) You need to add '0', as in charNumber[i]= (char)units + '0'

John Hascall
  • 9,176
  • 6
  • 48
  • 72