int to char

Hello to all

I have an integer that works like a counter and I have to put the content of the count in a char type. I try like this:

1
2
3
4
int aa++; // goes from 0 to 255
char a;

itoa(aa, a, 8);


It says itoa function cannot be resolved,
Exist other way to do this?


Regards
Last edited on
Read up on the function before you try to use it:
http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/

Note that it's not standard and not guaranteed to exist. Your implementation may or may not provide it. However, as it is, even if it does exist, you're trying to call some other function entirely because you've got the input parameters wrong.


char * itoa ( int value, char * str, int base );
The first variable must be an int. Fine.
The second variable must be a char*. You're trying to pass it a char. A char is not a char*. You must pass it a char*.
The third variable must be an int. Fine.

Last edited on
int aa++; is not a valid identifier.

For the function, try changing char a; to char *a;.
For the function, try changing char a; to char *a;


Don't forget to ensure that it does actually point to memory that belongs to you.
Moschops wrote:
Don't forget to ensure that it does actually point to memory that belongs to you.

That too.
Hello,

what about doing like this:
 
a = static_cast<char>(aa);


seems ok?

Regards
Last edited on
Hello,

Anyone can give me an idea of how is the best way to check if all this conversions goes ok.

Regards,
CMarco
I wouldn't have thought so. That would turn, for example, the number 7 into the unprintable character known as BEL, and the number 75 into the character K. I doubt that's what you want.

This is because a char is stored as a number in a single byte, and the numbers are mapped to letters as shown in this table:
http://www.asciitable.com/
Hello,
what about doing like this:
a = static_cast<char>(aa);
seems ok?

No, not even close to OK! But this is more than OK: a=aa+'0';
But this is more than OK: a=aa+'0';


If you do this, remember that if aa is more than one digit long (i.e. greater than nine), you're asking for trouble. Again, see http://www.asciitable.com/ to work out how this works.
Last edited on
And, here's my program that transforms an any-digit number to a char*, as a standard alternative to itoa():
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
inline int mypow(int a, int b)
{
    if (b==0) return 1;
    if (a==0) return 0;
    return a*mypow(a, b-1);
}

int main()
{
    int num=1029384756;
    const int n=int(log(num)/log(10)+1);
    char* num_string=new char[n];
    num_string[n]='\0';
    for (int i=n-1, j=0; i>=0; i--, j++)
    {
        num_string[j]=int(num%int(mypow(10, i+1)))/int(mypow(10, i))+'0';
        }
    cout<<num_string;
    system("pause");
}
Use sprintf() for itoa() replacement, or, if you are not limited to C language, use a std::stringstream.
thanks to all for the awesome advises...

Regards,
CMarco
Topic archived. No new replies allowed.