How to convert data type int to char?

I would like to convert a data type int to char.

For example, i would like to convert int a = 100 into char a[0] = '1', a[1] ='0' , a[2] ='0'.

i had tried itoa function which gave me the error message of "error: use of undeclared identifier 'itoa'".

AnyOne pls help, thank you.
You need to include the stdlib header in your program:

1
2
3
4
5
6
7
8
9
10
#include <stdlib.h>

int main()
{
	int a(100);
	char buffer[4];
	itoa(a, &buffer[0], 10);

	return 0;
}
From http://www.cplusplus.com/reference/cstdlib/itoa/
This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.


ajh32's code above does not compile on C++ Shell (including either <stdlib.h> or <cstdlib>)

 In function 'int main()': 7:24: error: 'itoa' was not declared in this scope


But if you're compiler does support itoa (or ltoa)...

You need to include the stdlib header in your program:

If compiling as .cpp could include <cstdio> instead.

And stack space isn't that limited, so no need to use as tight a buffer as possible.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstdlib> // now using C++ header

int main()
{
    int value = 100;
    char buffer[32] = ""; // plenty of space (and zero init)
    itoa(value, buffer, 10); // no actual need to take address of first elem
    std::cout << buffer << "\n";
    return 0;
}


An alternative, pre-C++11, ANSI compliant solution is to use std::ostringstream (this does work with C++ Shell)
http://www.cplusplus.com/reference/sstream/ostringstream/

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <sstream>
#include <string>

int main()
{
    int value = 100;
    std::ostringstream oss;
    oss << value;
    std::cout << oss.str() << "\n";
    return 0;
}


Andy

PS The maximum decimal value of a 64-bit int is -9223372036854775807 (21 chars)
Last edited on
Look like i have a long way to go.... there are a lot of function and code which i never see before. Anyway, Thank you everyone!
Topic archived. No new replies allowed.