如何从C风格的constchar*数组中提取整数

How to extract integer from C style const char* array

本文关键字:数组 提取 整数 constchar 风格      更新时间:2023-10-16

我正试图从C风格的const char*数组中提取一个整数。

到目前为止,我有这个:

int Suite::extractParameter(const char* data)
{
    //Example data "s_reg2=96"
    const char *ptr = strchr(data, '=');
    if(ptr)
    {
        int index = ptr - data;
        //Get substring ie. "96"
        //Convert substring to int and return
    }
    else return -1;
} 

但我不知道如何提取子字符串,然后将其转换为整数。

要提取的整数介于0和9999之间。

如果字符串总是在'='字符的末尾,则可以使用std::atoi:

const char *ptr = strchr(data, '=');
if(ptr && *(ptr+1)) { // it's not NULL and not the last character
    int val = std::atoi(ptr+1);
}

演示。