我有一个不断填充的字符的环形缓冲区数组,两个位置之间的数据:counter和counter2。我需要提取该数据并将其与文字字符串进行比较。
我正确地获取了数据并将其放置在str数组中,但是无法正确获取它来找到我想要的字符串文字。在这种情况下,我想从以下位置找到字符串“ OK”:
AT
OK
使用此代码:
#define BUFFER_SIZE 512
volatile int rxn=0; // buffer 'element' counter.
volatile char rx[BUFFER_SIZE];
volatile uint8_t rxFlag = 0;
void getData(){
int counter, counter2;
counter=rxn;
///some time has passed
counter2=rxn;
char str[1024]={'\0'};
for (int i=counter ; i!=(counter2) ; i=(i+1)%BUFFER_SIZE){
str[i]=rx[i];// grab the data
}
for (int i=0; i<1024; i++){
print(str[i]); // print all the data
}
if(strstr(str, "OK") != NULL){
print("found"); // this never executes.
}
}
但是,永远不会找到“确定”。文字字符串应为“ AT \ nOK \ n \ 0”或“ AT \ nOK \ 0”。为什么代码片段不起作用?
//这永远不会执行
问题不在于调用strstr
方法的方式,而在于您填充的方式str
。
运行此单元测试以确信该方法:
#include <stdio.h>
#include <string.h>
int main(void) {
char str[] ="AT\nOK\n\0"; // Same for 'AT\nOK\0'
if(strstr(str, "OK") != NULL){
printf("found"); // will be printed
}
return 0;
}
正如@@ hyde所评论的那样:您将数据从环形缓冲区复制到中间的某个位置str
,除非它counter
为0。所以str
将从0开始,IOW是一个空字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句