OneBite.Dev - Coding blog in a bite size

convert variable from string to int in C

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

#include <stdio.h>
#include <stdlib.h>

int main () {
  char str[5];
  int num;

  strcpy(str, "4");
  num = atoi(str);
  printf("The integer value of the string is %d", num);
  return 0;
}

The code above is a sample code for how to convert a string to an integer in C. The code begins with two library inclusions: stdio.h and stdlib.h. Then, a character array ‘str’ and integer variable ‘num’ are declared. A string “4” is copied to the str array using the strcpy function. Afterwards, the atoi() function is used in order to convert the string to an integer, which will be stored in variable num. Finally, the printf() function is used to print out the integer value of the string, that is, the value 4.

c