【问题标题】:Parsing AT Command string into integer将 AT 命令字符串解析为整数
【发布时间】:2021-09-10 12:06:48
【问题描述】:

我有以下以错误代码结尾的字符串int。比如0511512513

我想得到那个号码。

字符串是这样的:

+QIND: "FOTA","END",0

0 是错误代码。

这是我的试验:

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

int main()
{
    // your code goes here
    char tempdata[40] = "FOTA\",\"END\",0";
    char* res = strstr(tempdata, "FOTA\",\"END\"");
    if(res != NULL)
    {
        int percentage = atoi(res + strlen(tempdata) + 1);
        cout << percentage << endl;
    }
    return 0;
}

【问题讨论】:

  • - 这对你有什么影响?

标签: c++ string integer


【解决方案1】:

好的,我没有解析或其他任何东西就解决了它

int value;
if(sscanf(tempdata, "FOTA\",\"END\",%d", &value)>0)
{
    
    cout<<value;
}

【讨论】:

  • 在您的回答中,您写道:"I solved it without a parsing" -- 此语句不准确,因为您的程序正在解析字符串。你所做的是,你让sscanf 做所有的解析,而不是自己做。不解析字符串是无法解决这个问题的。
【解决方案2】:

你可以像这样使用正则表达式:

#include <iostream>
#include <regex>

using namespace std;

int main(int argc, char** argv)
{

    string input = R"(+QIND: "FOTA","END",5)"; // Use raw string literal to avoid escaping "
    smatch matches;

    regex r(R"(\+QIND: "FOTA","END",(\d+))");
    regex_match(input, matches, r);
    
    if(matches.size() == 2)
        cout << "Number is " << matches[1] << endl;

    return 0;
}

【讨论】:

    猜你喜欢
    • 2020-11-11
    • 2019-09-04
    • 1970-01-01
    • 2021-11-03
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多