-4
int num = 123;
char num_charr[sizeof(char)];
std::sprintf(num_char, "%d", num);

how to convert int the same way without using sprintf? I Only Need The Code To Convert Without print.

Grim
  • 3
  • 3
  • 2
    `sizeof(char)` is `1` by definition. Your array can only hold a single character, and trying to write the four characters that `"123"` requires triggers undefined behaviour. Fix the array's size and use `std::snprintf` instead. – Quentin May 21 '22 at 14:17
  • What's the problem with the sprintf version that you would like to fix? (besides the buffer overrun...) – Aykhan Hagverdili May 21 '22 at 14:18
  • 3
    Unless this is some academic restriction you probably want to use `std::string` instead of char arrays in `c++` then the conversion and usage is simple: [https://en.cppreference.com/w/cpp/string/basic_string/to_string](https://en.cppreference.com/w/cpp/string/basic_string/to_string) – drescherjm May 21 '22 at 14:30
  • thank for help it, the variable 'num' was an example, in full code sprintf had a variable from 'for' which increased by one in loop, after turning on the code my application crashed and I thought the reason was using sprintf so I was looking for the conversion itself without displaying it. I copied this int to char substitution from the internet and I did not notice that in the place of char for sizeof there should be an int variable that is to be converted, i.e. 'num'. Now I have no crashes anymore, thanks for your help. – Grim May 21 '22 at 14:32
  • 2
    Be cautious copying code from the Internet without understanding how and why the code works. There are a lot of folks out there who think they are much better C++ programmers than they are or are operating in an interesting problem space where C++ idioms are not a viable solution. If you understand what the code does and why the programmer did it that way, you can better discern if their solution also suits your problem. In C++ `sprintf` is usually the wrong place to start. [See if any of the solutions offered here fit your needs](https://stackoverflow.com/questions/5590381). – user4581301 May 21 '22 at 14:42

1 Answers1

0
char num_charr[12]; // space for INT_MIN value -2147483648
itoa( num, num_charr, 10 );

Note: itoa is not supported on all compilers.

i486
  • 6,491
  • 4
  • 24
  • 41