簡體   English   中英

如何檢查用戶輸入的字符串是否與某項相同

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

我有此代碼示例。 有一個scanf可以保存鍵盤(例如Lotus)的輸入String值。 但是,即使我正確輸入了Lotus這個詞,它也不會執行相關的if語句。 **我的scanf函數有什么問題嗎???

#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';
                    }
                }   
             }
          }
      }

在C中比較兩個字符串時要小心。應使用string.h庫中的strcmp函數,如下所示:

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

當您編寫if(houseType=="Lotus")您實際上是在比較兩個字符串的基地址,而不是它們的實際內容。

在C語言中,不能使用==比較字符串。 這是因為字符串不是C中的基本數據類型,也就是說C本質上不了解如何比較它們-您必須使用函數。

比較C語言中的字符串的標准函數是strcmp() ,例如:

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

為了進一步解釋,您最初使用housetype == "Lotus"比較字符串的嘗試實際上是將存儲字符數組houseType的第一個字符的地址與存儲字符數組"Lotus"的第一個字符的地址進行比較。

發生這種情況是因為C中的字符串只是字符數組-它們不是固有的數據類型,因此C不能理解整數數組和字符數組之間的區別,它們都只是在數組中某個位置連續排列的數字內存,它會這樣對待它們,除非您專門使用對它們進行操作的代碼作為字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM