Arduino中的字符串提取问题
String extraction issue in 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,"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到该地址,任何人都可以在没有密码的情况下访问它,任何人都可以开始攻击它,所以我会隐藏它。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 编译包含字符串的代码时遇到问题
- 在C++中使用重载提取运算符时出现问题
- 在 Qt(C++) 中使用 QProcess 解压缩 - 提取目录问题
- 使用 substr 提取文本文件时出现问题
- 如何解决系统.Zip.TZipFile.ExtractAll无法从.zip文件中提取所有数据的问题
- 从位图提取像素数据的问题
- 从微妙的问题中提取单词
- 在 c++ 中从 txt 文件中提取条目的代码优化问题
- Arduino中的字符串提取问题
- 遍历 QHash 并提取重复值的键时遇到问题
- 简化__VA_ARGS__问题:无法提取 NULL
- 提取一个QMenu的宽度?奇怪的问题
- 网络爬虫链接提取问题