OneBite.Dev - Coding blog in a bite size

convert variable from string to boolean in C

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

  int main()
  {
    char string[10];
    bool boolean;
    scanf("%s", string);

    if (strcmp(string, "true") == 0)
    {
      boolean = true;
    }
    else if (strcmp(string, "false") == 0)
    {
      boolean = false;
    }

    return 0;
  }

This code enables us to convert a string variable to a boolean variable in C. First, it declares the variables string (which is an array of characters) and boolean. Then, it uses scanf() to read the input string. After that, it uses strcmp() to compare the string with “true” or “false” - this function returns 0 if the two strings are the same. If the result of strcmp() is 0, the boolean variable is set to true or false, depending on which string was compared with strcmp(). Finally, the program terminates.

c