Arduino中的字符串提取问题

String extraction issue in Arduino

本文关键字:提取 问题 字符串 Arduino      更新时间:2023-10-16

我有以下Arduino代码

#include "SIM900.h"
#include <SoftwareSerial.h>
#include "inetGSM.h"
#include<String.h>
InetGSM inet;

char msg[165];
char store[2];
char a;
char b;
char* disp;
boolean started=false;
void setup()
{
     //Serial connection.
     Serial.begin(9600);
     Serial.println("GSM Shield testing.");
     //Start configuration of shield with baudrate.
     //For http uses is raccomanded to use 4800 or slower.
     if (gsm.begin(2400)) {
          Serial.println("nstatus=READY");
          started=true;
     } else Serial.println("nstatus=IDLE");
     if(started) 
     {
          //GPRS attach, put in order APN, username and password.
          //If no needed auth let them blank.
          if (inet.attachGPRS("TATA.DOCOMO.INTERNET", "", ""))
               Serial.println("status=ATTACHED");
          else Serial.println("status=ERROR");
          delay(1000);

          //TCP Client GET, send a GET request to the server and
          //save the reply.
          inet.httpGET("www.boat.esy.es", 80, "/retrieve.php", msg, 165);
          //Print the results.

          Serial.println("nData received:");
          disp = strstr(msg,"rnrn");
          disp = disp+4;
          a = disp[1];
          b = disp[2];
     }
}
void loop()
{
  Serial.println("Begin");
  Serial.println(a);
  Serial.println("+");
  Serial.println(b);
  Serial.println("End");
  delay(500);
}

我的程序中的disp变量接受值1和1作为字符串。我希望这个 1 和 1 存储在两个单独的变量中。所以我尝试了上面提到的方法,这就是我得到的

输出

Begin
1
+
End
Begin
1
+
End
Begin
1
+
End

如果我正确理解数组,char arr[100]char* arr 相同,只是前者在内存上保留 100 个字符的位置,那么b = disp[2]应该给后一个11 1对吗?

我不是在尝试使用 String 库,因为这会占用大量内存。因此,如果有任何我不知道提取 1 并单独存储它们的方法,请告诉我。

谢谢你的时间!

你的代码几乎是正确的。

问题就在这里:

disp = strstr(msg,"rnrn");
disp = disp+4;  // now disp points to the string "11" (correct)
// what follows is wrong
a = disp[1];    // this is the second char element if the disp string
b = disp[2];    // this is the zero terminator of the disp string

你需要这个,因为在 C 数组中索引以 0 开头:

a = disp[0];
b = disp[1];

小型测试程序:

#include <stdio.h>
#include <string.h>
int main()
{
  char *disp;
  char msg[] = "Fake Headerrnrn12";
  char a;
  char b;
  disp = strstr(msg,"rnrn");
  disp = disp+4;
  a = disp[0];
  b = disp[1]; 
  printf("a = %cnb = %cn", a, b);
  return 0;
}

输出:

a = 1
b = 2

你的代码在这里有很多问题......首先,所有变量都是未初始化的,您在声明它们之后访问它们,而最初没有在内存中为它们提供任何值。要解决此问题,请在继续之前将每个变量设置为某些内容,然后继续如下:

char a = ''; // & so on...

接下来,char* disp;是一个指针,而不是一个变量。你实际上并不知道disp的物理位置,它指向它记忆的某个地方,也许是一点填充的内存,也许什么都没有。因此,在disp中存储某些内容的最佳方法是将其转换为数组,并且在需要时,它们会逐部分写入并终止变量。例如

char disp[2] = {}; // Declare disp...
disp[0] = '1';     // Write to disp...
disp[1] = '1';
disp[2] = '';

最后,您正在连接的Web服务器也附加了DynDNS到该地址,任何人都可以在没有密码的情况下访问它,任何人都可以开始攻击它,所以我会隐藏它。