比较用C两个字符串? [英] Comparing two strings in C?
本文介绍了比较用C两个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这code不工作,比较不被做,为什么?所有名称闯过如果。
的printf(请输入产品名称:\\ n);
scanf函数(%S,&安培; nameIt2);
的printf(输入内容:\\ n);
scanf函数(%S,&安培; descriptionI);
的printf(输入数量:\\ n);
scanf函数(%d个,&安培; qtyI);
的printf(请输入订购数量:\\ n);
scanf函数(%S,&安培; ordqtyI);而(的fscanf(FP4,%s%S%d个%S \\ n,&安培; namet2,&安培;内容描述,和放大器; qty2,&安培;!ordqty2)= EOF){
如果(namet2!= nameIt2)
fprintf中(fpt2,%s%S%d个%S \\ n,&安培; namet2,&安培;内容描述,qty2,&安培; ordqty2); }
解决方案
要比较两个C字符串(的char *
),使用的 的strcmp()
。该函数返回 0
在字符串是平等的,所以你需要这在code:
如果(STRCMP(namet2,nameIt2)!= 0)
如果你(错误地)使用
如果(namet2!= nameIt2)
您是通过指针比较两个字符串的(地址),当你有2个不同的指针(它总是在你的情况的情况下),这是不平等的。
This code is not working, the comparison is not being done why? All names get past the if.
printf("Enter Product: \n");
scanf("%s", &nameIt2);
printf("Enter Description: \n");
scanf("%s", &descriptionI);
printf("Enter Quantity: \n");
scanf("%d", &qtyI);
printf("Enter Order Quantity: \n");
scanf("%s", &ordqtyI);
while(fscanf(fp4, "%s %s %d %s\n", &namet2,&description2,&qty2,&ordqty2) != EOF){
if(namet2 != nameIt2)
fprintf(fpt2, "%s %s %d %s\n", &namet2, &description2, qty2, &ordqty2);
}
解决方案
To compare two C strings (char *
), use strcmp()
. The function returns 0
when the strings are equals, so you would need to this in your code:
if(strcmp(namet2, nameIt2) != 0)
If you (wrongly) use
if(namet2 != nameIt2)
You are comparing the pointers (addresses) of both strings, which are unequal when you have 2 different pointers (which is always the case in your situation).
这篇关于比较用C两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文