gpt4 book ai didi

c++ - C++ 函数调用中的字符串引用未更新

转载 作者:太空狗 更新时间:2023-10-29 20:19:09 24 4
gpt4 key购买 nike

我正在编写一个 arduino 库来在网络上发布 http 请求。

我正在使用 http://arduino.cc/en/Tutorial/TextString 中的 String 类

当我在函数调用后引用我定义的字符串对象时,我的代码表现异常。

这里实际上我试图获取我的 GET 请求的主体并从 http GET 请求的响应中删除 http header 。

说明如下:

方法调用:

  String body;  
if(pinger.Get(host,path,&body))
{
Serial.println("Modified String Outside :");
Serial.println(body);
Serial.println();
Serial.println("Modified String Outside Address");
Serial.println((int)&body);
}

输出

Modified String Outside :
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html
Content-Length: 113
Date: Wed, 13 Jan 2010 14:36:28 GMT

<html>
<head>
<title>Ashish Sharma
</title>
</head>
<body>
Wed Jan 13 20:06:28 IST 2010
</body>
</html>


Modified String Outside Address
2273

方法说明:

bool Pinger::Get(String host, String path, String *response) {
bool connection = false;
bool status = false;

String post1 = "GET ";
post1 = post1.append(path);
post1 = post1.append(" HTTP/1.1");

String host1 = "Host: ";
host1 = host1.append(host);

for (int i = 0; i < 10; i++) {
if (client.connect()) {
client.println(post1);
client.println(host1);
client.println();
connection = true;
break;
}
}

int nlCnt = 0;
while (connection) {
if (client.available()) {
int c = client.read();
response->append((char) c);
if (c == 0x000A && nlCnt == 0) {
nlCnt++;
if (response->contains("200")) {
status = true;
continue;
} else {
client.stop();
client.flush();
break;
}
}
}
if (!client.connected()) {
client.stop();
connection = false;
}
}
response = &response->substring(response->indexOf("\n\r\n"),response->length());
Serial.println("Modified String: ");
Serial.println(*response);

Serial.println();
Serial.print("Modified String Address: ");
Serial.println((int)&response);
return status;
}

输出:

Modified String: 
Ø
<html>
<head>
<title>Ashish Sharma
</title>
</head>
<body>
Wed Jan 13 20:06:28 IST 2010
</body>
</html>

Modified String Address: 2259

从示例中可以看出,字符串引用对象在 Get 方法中为我提供了正确的字符串,但是当 Get 方法返回时,字符串内容的引用发生了变化。

最佳答案

如果我对你的代码的理解正确,你可能会想做这样的事情:

*response = response->substring(response->indexOf("\n\r\n"),response->length());

代替

response = &response->substring(response->indexOf("\n\r\n"),response->length());

也可能不需要传入指针(引用可能会使代码看起来更好)。

关于c++ - C++ 函数调用中的字符串引用未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2057523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com