Pilatus said:
Hi everybody,
I am beginner and I have a problem in this simple code : I want that the
char contents 01234567, but it don't work
Could you help me ?
int bin[8] ;
char *buf = new char [4];
Here you don't allocate enough memory to store '01234567' plus the zero
terminator; you will need to allocate at least a char array with 9
elements. If your program writes beyond the allocated array (which it does
when the sprintf() function is called) anything may happen; the program may
crash immediately, it may crash later at some arbitrary point or it may
even appear to work fine (but if murphy gets its way not at the customers
site).
for (int i = 0; i <= 7; i++)
{
tab = i ;
cout << tab ;}
sprintf(buf, "%d", tab);
You cannot convert an array to a char array like this. The "%d" format
specifier means that the sprintf function expects one integer to follow.
However you give it a pointer to the first element of the tab array. To
convert the numbers in an integer array you will have to do that one number
at a time; i.e. you will need a loop for this.
cout << "\nbuf=" << buf;
delete [ ] buf;
Rather than using C tricks, try to solve the problem the C++ way. Using the
std::string class and the std::stringstream you don't have to worry about
buffer overflows or format specifiers:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int tab[8];
// Fill tab array...
for(int i = 0; i <= 7; ++i)
{
tab = i;
cout << tab ;
}
cout << endl;
// Convert to string.
stringstream ss;
for(int j = 0; j <= 7; ++j)
{
ss << tab[j];
}
string s = ss.str();
// Output string.
cout << s << endl;
return 0;
}
Good luck!