解析AT指令字符串提取末尾整数类型错误码的实现问题
AT指令错误码提取问题解答
原代码存在的问题
- 指针偏移逻辑完全错误:
strstr返回的res是目标子串"FOTA\",\"END\"在tempdata中的起始地址,此时用res + strlen(tempdata) + 1会直接超出字符串的合法内存范围,属于野指针访问,atoi读取非法地址的结果完全不可预期。 - 未正确定位数字起始位置:匹配到目标子串后,只需要跳过整个目标子串的长度,再跳过子串后的逗号,就可以到达错误码的起始位置。
修复后的C风格实现(兼容原有代码逻辑)
#include <iostream> #include <cstring> using namespace std; int main() { // 可替换为实际接收到的AT返回字符串 char tempdata[64] = "+QIND: \"FOTA\",\"END\",512"; const char* target = "\"FOTA\",\"END\""; char* res = strstr(tempdata, target); if(res != NULL) { // 跳过匹配到的整个目标子串,再跳过后面的逗号 int err_code = atoi(res + strlen(target) + 1); cout << "提取到的错误码:" << err_code << endl; } return 0; }
更安全的C++风格实现(避免裸指针操作)
#include <iostream> #include <string> using namespace std; int main() { string tempdata = "+QIND: \"FOTA\",\"END\",513"; string target = "\"FOTA\",\"END\""; size_t pos = tempdata.find(target); if(pos != string::npos) { // 找到目标子串后第一个逗号的位置,往后就是错误码 size_t comma_pos = tempdata.find(',', pos + target.size()); if(comma_pos != string::npos) { int err_code = stoi(tempdata.substr(comma_pos + 1)); cout << "提取到的错误码:" << err_code << endl; } } return 0; }
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

