0

I am trying to convert an integer into a string of numerals stored in char *s.

char* ItoA(int n, char *s){ 
    int mod = n;
    for(int x = 1; x <= sizeof(n) + 2; x++){
        int digit = mod % 10;
        s[x-1] = digit;
        mod = mod / 10;
    }
    return s;
}

void main(){
    int n = 12345;
    char s3;
    // should print 12345
    cout << "\n" << ItoA(n, &s3);
    cin.get();
}

I know that something is wrong with my notation because I keep getting an array of garbage as the output in main. Why am I getting garbage instead of "12345"?

R Sahu
  • 204,454
  • 14
  • 159
  • 270
XeverSeven
  • 19
  • 1
  • 1
    There's [`itoa()`](http://www.cplusplus.com/reference/cstdlib/itoa) which is not standard c++ compliant. – πάντα ῥεῖ Feb 02 '15 at 21:49
  • Weird. I had assumed all the C library was included in C++. Any reason why it's not in standard C++? Is it C99 perhaps and therefore just hasn't been copied into C++ (yet)? ***Update again:*** seems like `itoa` isn't even standard C: http://stackoverflow.com/questions/10162733/atoi-is-a-standard-function-but-itoa-is-not-why – Aaron McDaid Feb 02 '15 at 21:52
  • 1
    You might use `snprintf` – Basile Starynkevitch Feb 02 '15 at 22:00
  • The character '0' and the value 0 are not equal. (Same for all the digits.) Your code behaves as if they are equal. – Rob Feb 02 '15 at 23:07

2 Answers2

1

Q: Why am I getting garbage instead of "12345"?

You are using &s3 as though it were an array of characters.

Use:

int main(){
    int n = 12345;
    char s3[20]; // Use an array of characters large enough to hold the number.
    // should print 12345
    cout << "\n" << ItoA(n, s3);
    cin.get();
}

Also, it's not clear to me what your logic is for using sizeof(n) below:

for(int x = 1; x <= sizeof(n) + 2; x++)
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

In order to convert a number to a string, you need to convert to ASCII by adding the character '0'. Also, you need to allocate enough memory to store all the characters and initialize the memory. Finally the logic of your for loop is broken, and it is generally easier to construct the string backwards and then reverse it.

#include <iostream>
#include <string.h>

using namespace std;

char* ItoA(int n, char *s, int bufLength){ 
    // Create the string in reverse order
    int i;
    for(i = 0; i < bufLength; i++){
        int digit = n % 10;
        s[i] = digit + '0';
        n /= 10;
        if (n == 0) break;
    }

    // Reverse the string.
    for (int j = 0; j <= i / 2; j++) {
        char c = s[j];
        s[j] = s[i - j];
        s[i - j] = c;
    }

    return s;
}

int main(){
    int n = 12345;
    char s3[6];
    memset(s3, 0, 6);
    // should print 12345
    cout << "\n" << ItoA(n, s3, 6);
    cin.get();
}
merlin2011
  • 71,677
  • 44
  • 195
  • 329