简体   繁体   中英

How to check if the User entered String is same as that of something

I have this code sample. There is a scanf to hold the input String values from keyboard (ie Lotus). But even if I type the word Lotus correctly It does not execute the relevant if statement. **Is there any problem with my scanf function???

#include<stdio.h>
    int main()
    {
        char landType,houseType[100],wantToContinue,wantToContinue2;
        float installment;
        wantToContinue='Y';
        while(wantToContinue == 'Y' || wantToContinue == 'y') {
            printf("Land Type : ");
            scanf(" %c",&landType); 
            if(landType == 'A') {
                printf("Type of House: ");
                scanf(" %s", houseType);
                if(houseType == "Lotus") { 
                   //this won't go inside if statement even if I type Lotus correctly
                    installment=4000000-500000;
                    printf("Monthly Installment : R.s %.2f\n",installment/120);
                    printf("Do you want to Continue?(Y/y or N/n) : ");
                    scanf(" %c",&wantToContinue2);                  
                    if(wantToContinue2 == 'Y' || wantToContinue2 == 'y') {
                        wantToContinue=wantToContinue2;
                        printf("\n");
                    }else{
                        wantToContinue='N';
                    }
                }   
             }
          }
      }

Be careful when comparing two strings in C. You should use the strcmp function from the string.h library, like so:

if(strcmp("Lotus", houseType) == 0)

When you write if(houseType=="Lotus") you are actually comparing the base address of the two strings and not their actual content.

In C, strings cannot be compared using == . This is because strings are not a basic data type in C, that is C does not inherently understand how to compare them - you must use a function instead.

A standard function for comparing strings in C is strcmp() , eg:

if (strcmp(houseType, "Lotus") == 0)
{
    // do some work if the strings are equal
}

To explain further, your initial attempt to compare strings using housetype == "Lotus" actually compares the address where the first character of the character array houseType is stored with the address where the first character of the character array "Lotus" is stored.

This happens because strings in C are just arrays of characters - they are not an inherent data type, C does not, as such, understand the difference between an array of integers and an array of characters, they are all just numbers arranged contiguously somewhere in memory and it treats them as such unless you specifically use code that operates on them as strings instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM