Search code examples
cstringcomparison

How can I declare a variable in C?


I am doing a code for my homework and it needs to ask the person from which continent they are

I have to do it on C and I am just learning this language right now

So, here I got so far

printf("Which continent are you from? ");
char continent[10];
scanf("%s",continent);

Now I set the different options that the program should look for (I'll only use two for the sake of this example)

char America[10];
char Europe[10];

Now, here is what I am trying to do:

America = (continent == "America" or continent == "america");
Europe = (continent == "Europe" or continent == "europe");

I know they are wrong and that that is not the way yo compare strings, but I just want to depict what I am trying to do.

if (America or Europe) {
    if(America){
     printf("wc");
    }
    if(Europe){
    printf("toilet");
    }
}

So, how can I compare the string and also tell the program that if the string is equal to a certain word, it should go in the "America" or "Europe" variable?


Solution

  • You can use strcmp() function. Be sure to #include <string.h>.

    scanf("%s, continent);
    if (strcmp(continent, "America") == 0) //if string matches
    {
        <do interesting stuff>
    }
    

    You could also use strcasecmp() to do case-insensitive compare. Note that this strcasecmp() isn't standard C but gcc supports it.
    You could also write your own function using for() loop to iterate through string and check each character using if(string1[i] == string2[i].