Arduino中的字符串提取问题

时间:2016-06-07 08:51:53

标签: c++ c arrays string arduino

我有以下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,"\r\n\r\n");
          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&amp; 1作为字符串。我想要1&amp; 1存储在两个单独的变量中。所以我尝试了上面提到的方式,这就是我得到的

输出

Begin
1
+

End
Begin
1
+

End
Begin
1
+

End

如果我正确理解数组,则char arr[100]char* arr相同,只是前者在内存中保留100个字符位置,然后b = disp[2]应该给后者{{1} } 1对吧?

我没有尝试使用String库,因为这会占用大量内存。因此,如果有任何方式我不知道提取的那些1和&amp;请单独存放,请告诉我。

感谢您的时间!

2 个答案:

答案 0 :(得分:2)

您的代码几乎是正确的。

问题在于:

disp = strstr(msg,"\r\n\r\n");
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 Header\r\n\r\n12";
  char a;
  char b;

  disp = strstr(msg,"\r\n\r\n");
  disp = disp+4;
  a = disp[0];
  b = disp[1]; 

  printf("a = %c\nb = %c\n", a, b);
  return 0;
}

输出:

a = 1
b = 2

答案 1 :(得分:-3)

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

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

接下来,char* disp;是指针,而不是变量。你实际上并不知道disp的物理位置,它指向某个地方的内存,也许是一些人口密集的内存,也许什么都没有。因此,在disp中存储内容的最佳方法是将其转换为数组,并在需要时按部分读取并以正确的格式终止变量。 例如

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

&安培;最后你连接的网络服务器也有DynDNS附加到地址,任何人都可以在没有密码的情况下访问它,任何人都可以开始攻击它,所以我会隐藏它。