比较C中的两个字符串? [英] Comparing two strings in C?

查看:186
本文介绍了比较C中的两个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码无效,未进行比较。为什么?所有名称都通过如果

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);
}


推荐答案

要比较两个C字符串 char * ),请使用 strcmp() 。当字符串相等时,函数返回 0 ,因此您的代码中需要这样:

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(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆