我有以下 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 & 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,"\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
关于c++ - Arduino 中的字符串提取问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37674722/