我无法从GET响应中提取我需要的数据 我只想记住介于" - "之间的charcaters。和" - "因为我不需要任何其他东西。我尝试使用while循环,如下所示但它不会工作
谢谢
String readString;
while (client.connected() || client.available()) {
char c = client.read(); //gets byte from ethernet buffer
while(c != "-"); //this throw error
readString += c; //places captured byte in readString
}
client.stop(); //stop client
Serial.print(readString);
String res = readString.substring("-","-"); //throw error
String val = "happy";
if(res == val){
Serial.print(res);
Serial.println(" happy");
}else{
Serial.print(res);
Serial.println(" sad");
}
Serial.println("==================");
Serial.println();
readString=""; //clear readString variable
答案 0 :(得分:0)
好的,这里有不同的问题。
c
)和字符串("-"
)。您应该使用'-'
与char进行比较。substring
功能。在任何情况下,substring
函数都需要INDICES,而不是chars。这就是说,这段代码适合你的情况:
// state =
// 0 -> waiting for first -
// 1 -> reading the answer and waiting for second -
// 2 -> finished reading
uint8_t state = 0;
while (client.connected() || client.available()) {
char c = client.read(); //gets byte from ethernet buffer
if ((c == '-') && (state < 2))
state++;
if ((state == 1) && (c != '-'))
readString += c;
}
client.stop(); //stop client
Serial.print(readString);
String val = "happy";
if(res == val){
Serial.print(readString);
Serial.println(" happy");
}else{
Serial.print(readString);
Serial.println(" sad");
}
无论如何,我真的不喜欢在arduino中使用变量大小的变量,因为你的内存很少(所以你为什么要浪费它?)。我的建议是始终使用固定大小的字符串(aka char数组)。例如:
// state =
// 0 -> waiting for first -
// 1 -> reading the answer and waiting for second -
// 2 -> finished reading
uint8_t state = 0;
char readString[MAX_SIZE+1];
uint8_t readStringIndex = 0;
while (client.connected() || client.available()) {
char c = client.read(); //gets byte from ethernet buffer
if ((c == '-') && (state < 2))
state++;
if ((state == 1) && (c != '-'))
{
readString[readStringIndex] = c;
readStringIndex++;
}
}
readString[readStringIndex] = '\0'; // string terminator
client.stop(); //stop client
Serial.print(readString);
if(strcmp(readString, "happy")){
Serial.print(readString);
Serial.println(" happy");
}else{
Serial.print(readString);
Serial.println(" sad");
}
修改强>
OP提到字符串不再由两个' - '分隔,而是包含在'&lt;'之间和'&gt;'。
因此,应该以这种方式修改代码:
// state =
// 0 -> waiting for first -
// 1 -> reading the answer and waiting for second -
// 2 -> finished reading
uint8_t state = 0;
char readString[MAX_SIZE+1];
uint8_t readStringIndex = 0;
while (client.connected() || client.available()) {
char c = client.read(); //gets byte from ethernet buffer
switch (state)
{
case 0: // Waiting for first char
if (c == '<')
state = 1;
break;
case 1: // Reading the answer and waiting for second char
if (c == '>')
state = 2;
else
{
readString[readStringIndex] = c;
readStringIndex++;
}
break;
}
}
readString[readStringIndex] = '\0'; // string terminator
client.stop(); //stop client
Serial.print(readString);
if(strcmp(readString, "happy")){
Serial.print(readString);
Serial.println(" happy");
}else{
Serial.print(readString);
Serial.println(" sad");
}