OneBite.Dev - Coding blog in a bite size

convert variable from int to string in C

Code snippet on how to convert variable from int to string in C

  int number = 32;
  char str[10];
  sprintf(str, "%d", number);

This code converts a numerical value from an integer to a string. First, an integer named “number” is declared and assigned a value of 32. This is followed by the definition of a character array named “str”, which is large enough to store the digit characters of the number. The sprintf() function is then used to convert the numerical value of the integer to a string and this is stored in the “str” character array. This function is given two arguments - the first is the string to store the result in, and the second is the numerical value, in this case “number”. The result of the conversion is then stored in the “str” character array.

c