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