0

I'm trying to reverse the digits of an integer. To do this I am:

  1. Taking the integer.
  2. Putting it into a string.
  3. Putting the string into another string in reverse.
  4. Converting the reversed string to a proper integer.

I've sort of gotten to step 3, and while it does reverse the string properly, it leaves me with a lot of odd data. The Results The top part is just the array lengths to compare. What is happening for this odd data?

int ReverseNumber(int Num) {
//Variables
int i = 0;
int j = 0;
char Number[50];
char ReversedNumber[50];
sprintf(Number,"%d", Num);

//Finding Length Of Array
do{ 
    i++;
}while(Number[i] > 10);
//i - 1(Due to Array Length)
i--;

//Reverseing
do {
    printf("%d | %d \n",j,i);
    ReversedNumber[j] = Number[i];
    printf("%c\n", ReversedNumber[j]);
    getch();
    i--;
    j++;
} while (i != -1);

int NumberLength = (strlen(Number) - 1);
//Printing
printf("%s\n", Number);
printf("%s\n", ReversedNumber);
}
rwp
  • 1,786
  • 2
  • 17
  • 28
VallyMan
  • 135
  • 5
  • 1
    Why do you have this weird `do`/`while` loop to find the length of `Number` when you could just use `strlen`? And why do you later do `int NumberLength = (strlen(Number) - 1);` but never use `NumberLength`? – melpomene May 06 '18 at 14:59
  • 1
    Your code doesn't terminate `ReversedNumber`. – melpomene May 06 '18 at 15:00
  • Isn't this because you make An Array with lenght 50, C and C++ fill unused memory with strange objects as I remember correctly (been some time I programmed in C) – Stan Fieuws May 06 '18 at 15:01
  • 1
    @StanFieuws C and C++ don't do that. It's the compiler that do that for debugging purpose. In MSVC [uninitialized memory will be filled with 0xCC](https://stackoverflow.com/q/370195/995714) and that's why `╠╠╠╠╠...` is seen (it's 0xCC in the [code page 437](https://en.wikipedia.org/wiki/Code_page_437) which is the default in most PCs that use Western codepage) – phuclv May 06 '18 at 15:51
  • @LưuVĩnhPhúc oke, thanks for clearing that up for me :) – Stan Fieuws May 06 '18 at 15:52

1 Answers1

2

You have to add \0 to the end of ReversedNumber after the reversing do {...} while (...) terminates:

//Reverseing
do {
...
} while (...);
ReversedNumber[j] = '\0';
medalib
  • 937
  • 1
  • 6
  • 7