You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GPS系统NMEA解析器测试中WPL格式检测失败原因排查

GPS NMEA解析器WPL格式测试失败问题排查

错误信息

tests/nmea/nmea-parser-tests.cpp(28): [1;31;49merror: in "IsSupportedFormat/SupportedFormats": check isSupportedFormat("WPL") has failed[0;39;49m

相关代码段

#include <iostream> // For debugging
#include <stdexcept>
#include <cmath>
#include <regex>
#include <iostream>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include "nmea/nmea-parser.h"
#include <cassert>
#include <vector>

using namespace std;

namespace GPS::NMEA
{
  bool isSupportedFormat(std::string theSentence)
  {
      
      unsigned startOfData = theSentence.find("P"); //gets the start of the data by finding the first P (which will be on the end of $GP)
      
      unsigned endOfData = theSentence.find(","); //gets the first comma (which will be straight after the data we need)
      string theData = theSentence.substr(startOfData + 1, endOfData - startOfData - 1); //this stores the data inbetween the P and then ,(this splits the data we need away from the full sentence)
      
      if (theData == "GLL") { //checks if the data reads GLL
          return true;
      }
      else if (theData == "WPL") { //checks if the data reads WPL
          return true;
      }
      else if (theData == "RMC") { //checks if the data reads RMC
          return true;
      }
      else if (theData == "GGA") { //checks if the data reads GGA
          return true;
      }
      else {
          return false; //If none of the data matches up correctly then this will return false.
      }
  }
}

问题原因

你的函数逻辑是从带$GP前缀的完整NMEA语句中提取格式标识,但测试用例直接传入了纯字符串"WPL":

  1. 当输入是"WPL"时,theSentence.find("P")会返回string::npos(字符串中不存在字符'P')
  2. 基于无效索引执行substr操作,会导致theData成为空串或乱码,无法匹配"WPL",最终返回false,测试失败。

修复方案

方案1:兼容两种输入场景(推荐)

修改函数逻辑,同时支持完整NMEA语句和纯格式标识:

bool isSupportedFormat(std::string theSentence)
{
    std::string theData;

    // 检查是否为完整NMEA语句(包含$GP前缀和逗号分隔符)
    size_t pPos = theSentence.find("P");
    size_t commaPos = theSentence.find(",");
    if (pPos != std::string::npos && commaPos != std::string::npos && pPos < commaPos) {
        theData = theSentence.substr(pPos + 1, commaPos - pPos - 1);
    } else {
        // 若为纯格式标识,直接使用输入字符串
        theData = theSentence;
    }

    // 统一转为大写,避免大小写不匹配问题
    boost::to_upper(theData);

    // 简化判断逻辑
    return theData == "GLL" || theData == "WPL" || theData == "RMC" || theData == "GGA";
}

方案2:调整测试用例

如果函数设计仅接受完整NMEA语句,将测试输入改为"$GPWPL,xxxx..."这类符合规范的语句格式。

内容的提问来源于stack exchange,提问作者F02

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 20:05:26