[英]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.