Search code examples
cif-statementchars

C programming language :if statements are not working correctly with characters


I'm trying to make this program say good but it says okay instead though I made the variable value the same of the if test value

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

int main()
{
    char history[200];
    history == "NY school";

    if(history == "NY school")
    {
        printf("good");
    }
    else{printf("okay");}
    return 0;
}

Solution

  • This should work for you:

    #include <stdio.h>
    #include <string.h>
            //^^^^^^^^ Don't forget to include this library for the 2 functions
    
    int main() {  
    
        char history[200];
        strcpy(history, "NY school");
      //^^^^^^^Copies the string into the variable
        if(strcmp(history, "NY school") == 0) {
         //^^^^^^ Checks that they aren't different
            printf("good");
        } else {
            printf("okay");
        }
    
        return 0;
    
    }
    

    For more information about strcpy() see: http://www.cplusplus.com/reference/cstring/strcpy/

    For more information about strcmp() see: http://www.cplusplus.com/reference/cstring/strcmp/