如何将char数组与字符串进行比较

时间:2012-06-04 02:42:54

标签: c arrays string filter compare

我的程序是从Zigbee接收数据并过滤它以获得我想要的内容。

unsigned char idata buff[100];            //To read data from rawrxd[] and process data
unsigned char count=0;                    //To store counter for rawrxd[]
unsigned char buff_count=0;               //store counter for buff[], read counter for rawrxd[]
if(buff_count!=count)                   //checking Is there any unread data?
    {
        if(buff_count==100)                 //go back to start position of array
        buff_count=0;

        buff[buff_count] = rawrxd[buff_count];  //read the data

        if(strcmp(buff, "UCAST:000D6F0000A9BBD8,06=!221~@") ==0)
        {
        ES0=0;
        Serial_txString("AT+UCAST:000D6F0000A9BBD8=!222~@");
        tx(0x0D);
        tx(0x0A);
        ES0=1;
        }

        if(strcmp(buff, "UCAST:000D6F0000A9BBD8,06=!221#@") ==0)
        {
        ES0=0;
        Serial_txString("AT+UCAST:000D6F0000A9BBD8=!222#@");  
        tx(0x0D);
        tx(0x0A);
        ES0=1;
        }

        buff_count++;                           //increase the read_count
    }

这应该是缓冲区将如何接收UCAST,然后将其与字符串进行比较,如果相同,则返回0。 但是,它只比较一次,之后我收到了下一个UCAST,它根本没有比较。

此外,第一次比较必须相同才能工作。如果收到错误的字符然后收到正确的字符它将无法正常工作。从这,它是指针问题?因为我的缓冲区是一个char数组,我试图将它与字符串进行比较。

2 个答案:

答案 0 :(得分:0)

问题是在进行字符串比较之前buff[]没有NUL字符。所以strcmp()没有感觉到你认为应该接收到的字符串的结尾(而是看到之前在数组中留下的内容),所以它永远不会匹配。

     buff [buff_count] = rawrxd[buff_count];  //read the data
     buff [++buff_count] =  '\000';       /*  you need to add this */

如果其他情况良好,那么strcmp()有机会工作。

另外,我很确定你可以整理和优化代码序列

    Serial_txString("AT+UCAST:000D6F0000A9BBD8=!222~@");
    tx(0x0D);
    tx(0x0A);

进入

    Serial_txString("AT+UCAST:000D6F0000A9BBD8=!222~@\x0d\x0a");

答案 1 :(得分:0)

通过指定方式:

buff[buff_count] = rawrxd[buff_count];

您只是将rawrxd缓冲区的第一个元素分配给buff变量。它是一个变量赋值,而不是指针赋值。

因为两者都有相同的缓冲区大小,所以只需要等同于这两个基本指针:

buff = rawrxd;

然后执行strcmp(),或者更好,使用strncmp(),因为字节数(元素)是固定的。

希望它有所帮助。

干杯!

相关问题